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.


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

Parameters Explanation:

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 is a parameter that has to be replaced by newSubstring.
The only the first occurrence will be replaced.

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

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


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial- 
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>replace method</title>
      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);


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

Leave a Reply

Your email address will not be published. Required fields are marked *