I have a long string, and a list of other strings, which I need to mark in the long string.
Say we have abcdefghijk
and the strings I need to mark are ghi
and abc
.
What is the simplest way to do it in Javascript and CSS? I thought about using the exec()
method that will return the starting index of the string in the long string.
Then, I'd have the starting index and the size of the string. So, I could find it in the long string. How could I highlight it? Maybe using CSS?
You can try this jQuery plugin. It's really straightforward...
How to use it?
1 - Download the plugin
jquery.highlight-3.js (2 KB) and reference it in your page just after jQuery.
2 - Style the highlight class
Create an entry in your CSS sheet:
.highlight { background-color: yellow }
3 - Highlight term/phrase
Call the highlight function with the text to highlight. To highlight all occurrences of “ghi” (case insensitive) that are within the form element, use the following code:
$('form').highlight('ghi');
4 - Remove highlighting
The highlight can be removed from any element with the removeHighlight function. In this example, all highlights under the element with the ID highlight-plugin are removed.
$('#highlight-plugin').removeHighlight();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With