1
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 are round, and oranges are juicy. , because of the case insensitivity, but instead it outputs Apples are round, and oranges are juicy.

Why??

1

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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);

Comments

0

Try:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.