5

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?

1
  • 1
    There's a highlight plugin for jQuery. The code is pretty short and simple, so you may be able to adapt it to your needs. Commented May 30, 2011 at 15:34

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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; 
}

1 Comment

Yes but this is what to do when you find the strings within the long string. You said you have already gotten the index and the length. Look at @Tyilo's answer which explains how to stick the span tags into the long string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.