Open In App

What is replace() Method in JavaScript ?

In JavaScript, the replace() method is a string method that is used to search for a specified substring or pattern in a string and replace it with another substring or the result of a function. It returns a new string with the replacements applied while leaving the original string unchanged.

Syntax:

string.replace(searchValue, newValue)

Example: Here, the replace() method is called on the str string to replace the substring “World” with “Universe”. The resulting string, "Hello, Universe!", is assigned to the variable newStr. Note that the original string str remains unchanged.




const str = "Hello, World!";
const newStr = str.replace("World", "Universe");
 
console.log(newStr); // Output: "Hello, Universe!"

Output
Hello, Universe!
Article Tags :