1

我想用 替换变量str'<span class="red">str'</span>但我总是得到"'"跨度的外部。我写了以下javascript:

var f1="XY+X'Y";
var str=X;
var patt=new RegExp(str+'\'',"g");
f1.replace(patt, "<span class=\"red\">"+str+"'"+"</span>")

我得到:

<span class="red">X</span>';

我想:

<span class="red">X'</span>;
4

2 回答 2

2

当我评估

var f1="XY+X'Y";
var str="X";
var patt=new RegExp(str+'\'',"g");
f1.replace(patt, "<span class=\"red\">"+str+"'"+"</span>")

我明白了

"XY+<span class="red">X'</span>Y"

我认为这是您的预期结果?也许您只需要仔细检查您的引号/字符串变量?

于 2012-04-17T18:23:40.253 回答
0

您正在正则表达式中搜索“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 :)

于 2012-04-17T18:32:49.567 回答