根据String.prototype.replace()
page on MDN的说法,我应该能够很容易地替换多个模式
str.replace('what to replace', 'replace with', 'flags')
并将标志设置为'g'
。
它在Firefox3.6中运行完美。但在Chrome和IE8中,它只取代了第一个'what to replace'
。
我可以使用
str.replace(/what to replace/gi, 'replace with')
语法。但是我将'what to replace'
从数组中提取出来,这使得在该语法中添加标志变得很困难。
这是我正在尝试使用的代码。如何修改它以在Chrome和Firefox中工作?
function generateQuestion()
{
//alert('variable length: '+variableList.length);
for(i=0;i<variableList.length;i++)
{
variable = variableList[i];
rep = replacementList[i];
flags = "gi";
questionText = questionText.replace(variable, rep, flags);
}
}
为什么我要费心去修改它呢?Chrome不应该像链接中描述的那样评估JavaScript吗?
发布于 2011-02-13 08:07:12
似乎webkit的string.replace实现可能没有第三个参数,因为对我来说,'foo'.replace('o','i','g')
会导致fio
。
但是,以下方法似乎可以正常工作:
'foo'.replace(/o/gi,'i')
另一种选择是:
'foo'.replace(new RegExp('o', 'gi'),'i')
https://stackoverflow.com/questions/4981501
复制相似问题