Friday, April 20, 2012

How to replace all instances of a character in a string with Javascript

The easiest would be to use a regular expression with g flag to replace all instances:
str.replace(/foo/g, "bar")
This will replace all occurrences. If you just have a string, you can convert it to a RegExp object like this:
var pattern = "foobar",
    re = new RegExp(pattern, "g");

No comments:

Post a Comment