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)
string
: The original string on which thereplace()
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!