I would like to replace variable str' with <span class="red">str'</span>, but I always get the "'" outeside of the span. I wrote the following javascript:
var f1="XY+X'Y";
var str=X;
var patt=new RegExp(str+'\'',"g");
f1.replace(patt, "<span class=\"red\">"+str+"'"+"</span>")
I get:
<span class="red">X</span>';
I want:
<span class="red">X'</span>;
You are searching for “X'” in your regex, and replacing it with
<span ...>X''</span>as far as I can see. There appear to be a few issues with your code, and I’m not sure how you expect to get either result (the one you get, or the one you want) from the given code. May I suggest this alternative?This will find X or X’ in the source and surround it with the red class span. If you only want to highlight X’, then take out the
?in the patt variable (the ? makes the apostrophe optional).Edit:
Soluction:
The problem was that I use replace twice on the same string. Something like this
this works for me:
Thanks anyway 🙂