JavaScript(JS) string method - replace

www.igift‮di‬ea.com

The replace() method is a string method in JavaScript that is used to replace a specified substring with another substring in a string.

Here is the syntax for the replace() method:

str.replace(searchValue, replaceValue)

Here, str is the original string you want to perform the replacement on, searchValue is the string to be replaced, and replaceValue is the string to replace the searchValue with.

The replace() method returns a new string with the searchValue replaced with the replaceValue.

By default, the replace() method only replaces the first occurrence of the searchValue. To replace all occurrences of the searchValue, you can use a regular expression with the global flag g:

str.replace(/searchValue/g, replaceValue)

Here is an example of using the replace() method:

let str = "hello world";
let result = str.replace("world", "everyone");
console.log(result); // "hello everyone"

In the example above, the replace() method replaces the string "world" in the str with the string "everyone". The resulting string is "hello everyone".

Here is an example of using the replace() method with a regular expression:

let str = "hello world";
let result = str.replace(/o/g, "0");
console.log(result); // "hell0 w0rld"

In the example above, the replace() method replaces all occurrences of the letter "o" in the str with the number "0". The resulting string is "hell0 w0rld".