00 Votes

JavaScript: Replace all occurrences of a string

Question by Chematik | 2012-06-07 at 22:15

I am trying to carry out a replacement in JavaScript using the following code:

str = "ababab";
str = str.replace("a","X");
 
alert(str);
// output: Xbabab

However, there is an error in my code! Only the first occurrence of "a" is replaced by "X". How can that be, what am I doing wrong?

ReplyPositiveNegative
22 Votes

If that's what you're doing, always only the first occurrence of the search string will be found and replaced. Try it this way:

str = str.replace(/a/g,"X");

With this solution, you are using a regular expression to perform the replacement. The pattern, in your case "a", is written between / and / and the g at the end means that we want to replace all occurrences.

To clarify it once again:

str = "abcd abcd abcd";
str = str.replace(/abc/g,"X");
alert(str); // output: Xd Xd Xd

In this example, it should be a little more clearly, what is searched for.
2012-06-07 at 22:38

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.