Skip to content

Replace all character in string JavaScript | Code

  • by

Use a regular expression with g flag to replace all character in string JavaScript. For it you have use replace() method with regular expression.

str.replace(/foo/g, "char")

Replace all character in string JavaScript

Simple example code escape the dot, since it’s a special character in regex.

<!DOCTYPE html>
<html>
<body>
  <script>
    let str = "Replace.all.dot.by.the character _"
    var res = str.replace(/\./gi, '_');

    console.log(res)

  </script>
</body>
</html>

Output:

Replace all character in string JavaScript

Note that dot doesn’t require escaping in character classes, therefore if you wanted to replace dots and spaces with underscores in one go, you could do:

s2.replace(/[. ]/g, '_');

Using i flag is irrelevant here, as well as in your first regex.

Replace a character at a particular index in JavaScript

In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.

You’ll need to define the replaceAt() function yourself:

String.prototype.replaceAt = function(index, replacement) {
    return this.substring(0, index) + replacement + this.substring(index + replacement.length);
}

And use it like this:

var hello = "Hello World";
alert(hello.replaceAt(2, "!!")); // He!!o World

Do comment if you have any doubts or suggestions on this Js replace topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading