1

我在将所有出现的字符串模式替换为另一个字符串时遇到了麻烦。我的字符串看起来像这样

"<TD>&nbsp;&nbsp;&nbsp;&nbsp;1.Rule<SPAN> <A style="TEXT-DECORATION: underline" id=RULE#I#000002$000000 class=anchorTag NAME:RULE#I#000002$000000?>xxxx</A>&nbsp;
<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);

但我发现这不起作用。我在这里错过了什么吗?

4

1 回答 1

3

您需要转义您正在创建正则表达式的字符串:

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

... new RegExp( escapeRegExp(lv_id) , 'g') ...

您的字符串包含 a $,它在正则表达式中具有特殊含义(行尾)。

于 2013-05-20T15:51:38.827 回答