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?
Related Topics
How to Replace multiple Texts at the same Time
Tutorial | 0 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
MySQL: Search and Replace directly in MySQL database
Tip | 1 Comment
JavaScript: Remove last character from string
Tip | 5 Comments
JavaScript: Show and hide HTML area by clicking a link
Tutorial | 0 Comments
Search and Replace in File Names
Tutorial | 0 Comments
JavaScript and jQuery: Replace content of an element by using innerHTML
Tutorial | 0 Comments
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.
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:
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:
In this example, it should be a little more clearly, what is searched for.
2012-06-07 at 22:38