Reputation: 1455
I have written a regular expression to highlight the matched phrase in a text by adding a span around the phrase. The text may contain <b>
and </b>
anywhere in the text and phrase is to be matched ignoring it.
Following is my code:
var phraseArray = phrase.split(" ");
var phraseRegex = "";
if (phraseArray.length > 1) {
var regexSuffix = '+([/\\s]|<\/b>|<b>)+';
for (var i = 0; i < phraseArray.length; i++) {
phraseRegex += phraseArray[i] + regexSuffix;
if (i == phraseArray.length - 2) {
regexSuffix = "";
}
}
} else {
phraseRegex = phrase;
}
text = text.replace(new RegExp('(' + '([,\\s]|<\/b>|<b>)+' + phraseRegex + '([\\s/,.*]|<\/b>|<b>)+' + ')', 'gi'), '<span class="highlighted"> $1 </span>');
If phrase is Airways Aviation
and text is:
> <b>Airways Aviation</b>. Airways Aviation .Airways Aviation. fra
> Jet Airways. Jet Airways (India A range of talented people make it
> happen every day at Airways Aviation, .
Following is the output:
<span class="highlighting"> <b>Airways Aviation</b>.</span> Airways Aviation .Airways Aviation. fra
> Jet Airways. Jet Airways (A range of talented people make it
> happen every day at<span class="highlighting"> Airways Aviation, .</span>
Second occurrence of Airways Aviation is not highlighted. What is the reason and how can it be enhanced?
Upvotes: 0
Views: 1709
Reputation: 12478
[EDIT based on your question edit]
[EDIT based on comment]
You have to use the g
flag for Global Match.
word
to be matched"(<b>)?"+word+"(</b>)?"
//may or maynot contain <b>
and </b>
at start and end, g
for match allvar str="<b>Airways Aviation</b>. Airways<b> Aviation</b> .Airways Aviation. fra Jet Airways. Jet Airways (India A range of talented people make ithappen every day at Airways Aviation, ."
function test(word){
word=word.split(" ").join("(<b>|</b>|\\s)*");
var re=new RegExp("(<b>)?"+word+"(</b>)?",'g');
console.log(str.replace(re,"<span class=\"highlighting\">$&</span>"));
}
test("Airways Aviation");
Working model
function test(word){
word=word.split(" ").join("(<b>|</b>|\\s)*");
var re=new RegExp("(<b>)?"+word+"(</b>)?",'g');
var str=document.getElementById('div');
str.innerHTML=str.innerHTML.replace(re,"<span class=\"highlighting\">$&</span>");
}
span.highlighting{
background-color:#ccc;
color:#fff;
}
<body>
<div id="div"><b>Airways Aviation</b>. Airways<b> Aviation</b> .Airways Aviation. fra Jet Airways. Jet Airways (India A range of talented people make ithappen every day at <b>Airways</b> Aviation, .</div>
<button onclick="test('Airways Aviation');">Change</button>
</body>
Upvotes: 1