Friday, September 5, 2025
HomeLanguagesJavascriptJavaScript Replace() Method

JavaScript Replace() Method

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.

Javascript




let stringReplace = "Geeks for neveropen is a great platform to learn Javascript";
let result = stringReplace.replace(/Geeks/, "GFG");
console.log('New string: ' + result);


Output

New string: GFG for neveropen is a great platform to learn Javascript

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

Javascript




let stringReplace = "Geeks for Geeks is a great platform to learn Javascript";
let result = stringReplace.replace(/Geeks/gi, "GFG");
console.log('New string: ' + result);


Output

New string: GFG for GFG is a great platform to learn Javascript
RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6638 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11866 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS