我在使用另一个字符串替换字符串模式的所有出现时遇到了麻烦。我的字符串看起来像这样
"<TD> 1.Rule<SPAN> <A style="TEXT-DECORATION: underline" id=RULE#I#000002$000000 class=anchorTag NAME:RULE#I#000002$000000?>xxxx</A>
<SCRIPT>function show(id){document.getElementById(id).style.visibility = "visible";}function hide(id){document.getElementById(id).style.visibility = "hidden";}</SCRIPT>
<NOBR><SPAN style="CURSOR: hand" id=RULE#T#000002$000000NAME:RULE#T#000002$000000 onmouseover="show('RULE#T#000002$000000')" onmouseout="hide('RULE#T#000002$000000',event)" onclick="button_click('RULE#T#000002$000000');" valign="top"><IMG style="VISIBILITY: hidden; CURSOR: hand" id=RULE#T#000002$000000 title="Maintain Rule Title" align=middle src="../../IRM/GBRFFNM/images/text_icon.png" width=12 height=12></SPAN></NOBR><NOBR><SPAN style="CURSOR: hand" id=RULE#A#000002$000000NAME:RULE#A#000002$000000 onmouseover="show('RULE#A#000002$000000')" onmouseout="hide('RULE#A#000002$000000')" onclick="javascript:button_click('RULE#A#000002$000000',event)" valign="top"><IMG style="VISIBILITY: visible; CURSOR: hand" id=RULE#A#000002$000000 title="Add Rule" align=middle src="../../IRM/GBRFFNM/plus.gif" width=12 height=12></SPAN></NOBR></SPAN></TD>"
我需要用RULE#A#000003 $ 000000替换id RULE#A#000002 $ 000000。这些ID是动态的。我搜索堆栈流,发现我需要创建正则表达式。这就是我所做的..
var lv_html = parent.innerHTML; ///Contains the string abovwe
var array = _eleid.split('#');
var array1 = array[2].split('$');
lv_id = array1[0] + '$'; // = RULE#A#000002$000000
var replace_id = stmt_cntr + '$' ; // = RULE#A#000003$000000
var html1 = lv_html.replace(new RegExp( lv_id , 'g'), replace_id);
但我发现这不起作用。我在这里错过了什么吗?
答案 0 :(得分:3)
您需要从以下位置转义正在创建正则表达式的字符串:
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
... new RegExp( escapeRegExp(lv_id) , 'g') ...
您的字符串包含$
,它在正则表达式中具有特殊含义(行尾)。