为什么这个正则表达式输出不正确?

时间:2010-12-28 11:48:20

标签: javascript regex

var re = /apples/gi;  
var str = "Apples are round, and apples are juicy.";  
var newstr = str.replace("apples", "oranges","gi");
document.write(newstr);

由于不区分大小写,它应该输出oranges are round, and oranges are juicy.,而是输出Apples are round, and oranges are juicy.

为什么?

5 个答案:

答案 0 :(得分:3)

该签名没有.replace()方法,而是使用您创建的正则表达式,如下所示:

var re = /apples/gi;  
var str = "Apples are round, and apples are juicy.";  
var newstr = str.replace(re, "oranges");

You can test it here

答案 1 :(得分:2)

似乎str.replace函数只有two parameters,而不是三个。

所以我猜你必须写

var newstr = str.replace(/apples/gi, "oranges");

代替。

答案 2 :(得分:2)

您的示例中的re变量由于某种原因未被使用。

var str = "Apples are round, and apples are juicy.";  
var newstr = str.replace(/apples/gi, "oranges");
document.write(newstr);

答案 3 :(得分:0)

尝试:

var str = "Apples are round, and apples are juicy.";  
var newstr = str.replace(/apples/gi, "oranges");
document.write(newstr);

答案 4 :(得分:0)

你永远不会使用re变量,而String.replace()的第三个参数是非标准的,所以它不适用于所有浏览器:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace