Why doesn't this regex output correctly?
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace("apples", "oranges","gi");
document.write(newstr);
It should output oranges ar开发者_运维问答e round, and oranges are juicy.
, because of the case insensitivity, but instead it outputs Apples are round, and oranges are juicy.
Why??
There's no .replace()
method with that signature, instead use the regex you created, like this:
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
You can test it here.
Seems that the str.replace
function only has two parameters, not three.
So I would guess you have to write
var newstr = str.replace(/apples/gi, "oranges");
instead.
The re
variable in your example is not in use for some reason.
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(/apples/gi, "oranges");
document.write(newstr);
Try:
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(/apples/gi, "oranges");
document.write(newstr);
You never use the re
variable and the third argument for String.replace() is non-standard so it won't work in all browsers:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
精彩评论