Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight specific strings in a given long string in Javascript

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?

like image 950
user756223 Avatar asked Nov 13 '22 22:11

user756223


1 Answers

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();
like image 121
Leniel Maccaferri Avatar answered Nov 17 '22 06:11

Leniel Maccaferri