var a = 'Construction,Airports,Construction|Commercial Construction,Construction|Education,Construction|Healthcare,Construction|Housing,Construction|Industrial Construction,Construction|Other,Construction|Ports,Construction|Rail,Construction|Residential Construction,Construction|Roads & Bridges,Social Infrastructure|Commercial Construction,Social Infrastructure|Education,Social Infrastructure|Healthcare,Social Infrastructure|Housing,Social Infrastructure|Other,Social Infrastructure|Residential Construction';

alert(a.replace('|', ',', 'g'));


在chrome上,它仅替换第一次出现的|,而在g函数的正则表达式形式中使用replace()标志,它将替换所有出现的字符:

alert(a.replace(/\|/g, ',', 'g'));


有人可以帮助我了解我在替换的第一种形式中做错了什么吗?这是预期的行为还是错误?

最佳答案

使用以下格式:a.replace(/\|/g, ',') jsFiddle example

根据MDN


  在String.replace方法中使用flags参数是
  非标。代替使用此参数,而使用RegExp对象
  带有相应的标志。

09-19 08:08