简体   繁体   中英

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?

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();

Well if you know the index of the start of the string and the length you could just simply put span tags around it. So your HTML would look like:

<span class="highlight">abc</span>def<span class="highlight">ghi</span>jk

And then you'd style the span in your CSS:

.highlight
{
    background-color:yellow; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM