1

I want to apply style(blue font) for the matching words in a particular string which may have more than one words. This string can have same word repeated as well.

Ex: String paragraph = "This is the string which will be matched against substring. The matching substring can be a single word or multple words composed string. "

String matchingString = 'string word'

Now i want to apply blue bold style to the matching words of both string and word in paragraph string.

Would you please help me out how to do this by javascript?

Advance thanks Robert.

1
  • 1
    on the "string paragraph text" there's no match for "string word". Anyway, just replace the word by <span class=blue>word</span>. Look at: w3schools.com/jsref/jsref_replace.asp Commented Jul 28, 2012 at 12:51

2 Answers 2

1

Suppose:

<div id="myDiv">This is the string which will be matched against substring. The matching substring can be a single word or multple words composed string.</div>

.some-class{
    color: blue;
    font-weight: bold;
}

then you could do like this to replace the words:

var elem = document.getElementById('myDiv');
var phrase = 'string word';
var regex = new RegExp(phrase.split(' ').join('|'),"gi");
//result   =>    /string|word/g
elem.innerHTML = elem.innerHTML.replace(regex,'<span class="some-class">$&</span>');

Live demo

Sign up to request clarification or add additional context in comments.

3 Comments

This works perfectly for case-insensitive by adding i in regexp. Thank you very much Engineeeeeeeeer...:)
@Robo You have not mentioned anything about case sensitivity, so I have provided the answer without i flag.However I have added i, and probably you can accept my answer.
Hi Engineer, Need one more favour on top of above solution... if i give var phrase = 'string word' (I have given extra space between words). after this word is not getting matched. Would you share any idea?
0
var text = "This is the string which will be matched against substring...";
var search = "string word";

var words = search.split(" ");
for (var i = 0; i < words.length; ++i) {
    text = text.replace(words[i], "<span style='color: blue;'>"+words[i]+"</span>");
}

document.write(text);

Test it here: http://jsfiddle.net/Zh6t9/

3 Comments

Would you give an idea to match string in substring? and case insensitive.
If you want case insensitive substring matching, @Engineer's solution is the right way to go... ;) Just replace "g" with "gi" in the regex.
Again if i add style in the paragraph string, it's messing up as below

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.