Open In App

What is replace() Method in JavaScript ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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)
  • string: The original string on which the replace() method is called.
  • searchValue: The substring or regular expression pattern to search for in the string.
  • newValue: The string or function that replaces the matched substring(s).

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.

Javascript




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


Output

Hello, Universe!

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads