【问题标题】:Javascript .replace() not workingJavascript .replace() 不起作用
【发布时间】:2013-11-03 17:33:08
【问题描述】:
carList = cars.innerHTML;
alert(carList);
carList = carList.replace("<center>","").replace("</center>","").replace("<b>","").replace("</b>","");
alert(carList);

到底为什么会发生这种情况?我尝试将其拆分为单独的 string.replace() 并给出相同的结果。

【问题讨论】:

标签: javascript replace


【解决方案1】:

.replace() 与字符串一起使用只会修复您所看到的第一次出现。如果您使用正则表达式执行此操作,则可以指定它应该是全局的(通过在之后使用 g 指定它),从而接受所有出现。

carList = "<center>blabla</center> <b>some bold stuff</b> <b>some other bold stuff</b>";
alert(carList);
carList = carList.replace(/<center>/g,"").replace(/<\/center>/g,"").replace(/<b>/g,"").replace(/<\/b>/g,"");
alert(carList);

有关工作示例,请参阅此fiddle

【讨论】:

    【解决方案2】:

    您可以使用正则表达式同时匹配所有这些:

    carList = carList.replace(/<\/?(b|center)>/g,"");
    

    匹配字符串末尾的 g 标志告诉 Javascript 替换所有匹配项,而不仅仅是第一个匹配项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-04
      • 2019-03-29
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 2012-05-13
      • 2011-01-14
      • 1970-01-01
      相关资源
      最近更新 更多