Dav*_* R. 17 javascript google-chrome
根据String.prototype.replace()MDN上的页面,我应该可以通过使用轻松替换多个模式
str.replace('what to replace', 'replace with', 'flags')
Run Code Online (Sandbox Code Playgroud)
并将标志设置为'g'.
它在Firefox 3.6中完美运行.但在Chrome和IE8中,它只取代了第一个'what to replace'.
我可以使用
str.replace(/what to replace/gi, 'replace with')
Run Code Online (Sandbox Code Playgroud)
句法.但我正在拉出'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);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我要打扰它呢?Chrome不应该像链接中描述的那样评估JavaScript吗?
Yi *_*ang 27
您链接到的页面提到:
String.replace方法中flags参数的使用是非标准的.对于跨浏览器兼容性,请使用带有相应标志的RegExp对象.
基本上,它应该只适用于Firefox.根据文档,您可以使用new RegExp以下命令动态生成正则表达式:
var regex = new RegExp(variable, 'gi');
questionText = questionText.replace(regex, rep);
Run Code Online (Sandbox Code Playgroud)
但是,这需要variable转义.
看来 webkit 的 string.replace 实现可能没有第三个参数,正如我的'foo'.replace('o','i','g')结果。fio
然而,以下似乎有效:
'foo'.replace(/o/gi,'i')
Run Code Online (Sandbox Code Playgroud)
另一种选择是:
'foo'.replace(new RegExp('o', 'gi'),'i')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10686 次 |
| 最近记录: |