根据String.prototype.replace()
page on MDN ,我应该能够通过使用轻松替换多个模式
str.replace('what to replace', 'replace with', 'flags')
并将标志设置为 'g'
。
它在 Firefox 3.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 吗?
最佳答案
您链接到的页面提到:
The use of the flags parameter in the String.replace method is non-standard. For cross-browser compatibility, use a RegExp object with corresponding flags.
基本上,它只适用于 Firefox。根据文档,您可以使用 new RegExp
动态生成正则表达式:
var regex = new RegExp(variable, 'gi');
questionText = questionText.replace(regex, rep);
然而,这将需要对 variable
进行转义。
关于javascript - 为什么 javascript 不能替换 Chrome 或 IE 中的全局标志,我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4981501/