您正在正则表达式中搜索“X”,并<span ...>X''</span>
据我所知将其替换为。您的代码似乎存在一些问题,我不确定您希望如何从给定的代码中获得任一结果(您获得的结果或您想要的结果)。我可以建议这个替代方案吗?
var f1="XY+X'Y";
var str="X";
var patt=new RegExp(str+"\'?","g");
f1.replace(patt, "<span class=\"red\">$&</span>")
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
var str =f1.replace(patt, "<span class=\"red\">"+str+"</span>").f1.replace(patt, "<span class=\"red\">"+str+"'"+"</span>")
this works for me:
var str =f1.replace(patt, "<span class=\"red\">"+str+"</span>");
var str2=str.replace(patt, "<span class=\"red\">"+str+"'"+"</span>");
Thanks anyway :)