Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript Replace() Method

Improve Article
Save Article
  • Last Updated : 23 Dec, 2022
Improve Article
Save Article

The replace() method in JavaScript is used to search a string for a value or any expression and replace it with the new value provided in the parameters. The original string is not changed by this method.

Syntax:

string.replace(searchVal,newVal)

Parameter: This method accepts two parameters. 

  • searchVal: It is the value that we want to replace in the existing string
  • newVal: It is the new value that is to be put in the place of searchVal.

Return Value: This method returns a new string where the desired values have been replaced.

Example 1: In this example, we will use the replace() method to replace a character from the original string but the replace method here does not replace the characters which are in lowercase.

HTML




<h1>Geeks for Geeks</h1>
<h3>replace() Method</h3>
 
<p>Original string:
  <span id="gfg">
    Geeks for geeks is a great platform to learn Javascript
  </span>
</p>
 
<p id="gfg1"></p>
<script>
    let stringReplace = document.getElementById("gfg").innerHTML;
    let result = stringReplace.replace(/Geeks/, "GFG");
    document.getElementById("gfg1").innerHTML = 'New string: ' +result;
</script>

Output:

JavaScript Replace()  Method

JavaScript Replace()  Method

Example 2: In this example, the replace() method replaces the words completely irrespective of their case.

HTML




<h1>Geeks for Geeks</h1>
<h3>replace() Method</h3>
 
<p>Original string:
  <span id="gfg">
    Geeks for Geeks is a great platform to learn Javascript
  </span>
</p>
 
<p id="gfg1"></p>
<script>
    let stringReplace = document.getElementById("gfg").innerHTML;
    let result = stringReplace.replace(/Geeks/gi, "GFG");
    document.getElementById("gfg1").innerHTML = 'New string: ' +result;
</script>

Output:

JavaScript Replace()  Method

JavaScript Replace()  Method


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!