I am trying to highlight matched strings in a div. The issue encountered here is I should be highlighting the string 'score' wherever it occurs in the string. But it matches with the string 'scoreboard' and highlights 'scoreb' string.
var res = $("#div").text();
console.log(res);
var regex = new RegExp("(^|\\s)score(\\s|<\/span>|$|,|\.)", "ig");
res = res.replace(regex, function(match) {
match = match.replace(/^\s/g, "");
match = match.replace(/\s$/g, "");
return ' <span style="background-color:#bebef8;color:#000;">' + match + '</span> ';
});
console.log(res);
$("#div").html(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="div" style="border:1px solid #000" contenteditable="true">
The total score on the scoreboard is +3 points.
</div>
The issue is because you're not escaping all the \
characters in the RegExp string; you missed the last two:
var regex = new RegExp("(^|\\s)score(\\s|<\\/span>|$|,|\\.)", "ig");
Also note that you can avoid the need to escape them at all by using a Regex literal instead:
var regex = /(^|\s)score(\s|<\/span>|$|,|\.)/ig;
var res = $("#div").text();
var regex = /(^|\s)score(\s|<\/span>|$|,|\.)/ig;
res = res.replace(regex, function(match) {
match = match.replace(/^\s/g, "");
match = match.replace(/\s$/g, "");
return ' <span style="background-color:#bebef8;color:#000;">' + match + '</span> ';
});
$("#div").html(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="div" style="border:1px solid #000" contenteditable="true">
The total score on the scoreboard is +3 points.
</div>