String replace() method in JavaScript

You can use the replace method in JavaScript to replace matched substring from regular expression and a string. This method does not change the string on which it is used. It returns a new string.

Syntax:

var newString = str.replace(regexp|subString, newSubstring|function)

Parameters Explanation:

regexp:
A regexp is a regular expression which can be object or literal.
The match or matches from the regular expression are replaced with newSubstring or value that is returned by a function.

subString:
subString is a parameter that has to be replaced by newSubstring.
The only the first occurrence will be replaced.

newSubstring:
newSubstring is a parameter that replaces its value with the matches by regexp or subString.

function:
This parameter invokes a function which returns value that replaces values that are matched by regexp or subString.

Example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial- 
     scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>replace method</title>
    <script>
      var str = `My name is John.`;
      var substring = "John";
      var regexp = /John/gi;
      var newSubstring = "James";

      var replacedString = str.replace(substring, newSubstring);
      document.write("Replaced string is: ", replacedString);
      document.write("<br />");
      var replacedString = str.replace(regexp, newSubstring);
      document.write("Replaced string is: ", replacedString);
    </script>
  </head>
<body>
</body>
</html>

Output:

Replaced string is: My name is James.
Replaced string is: My name is James.

Leave a Reply