JavaScript(JS) string method - replaceAll

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

Here is the syntax for the replaceAll() method:

str.replaceAll(searchValue, replaceValue)
‮:ecruoS‬www.theitroad.com

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 replaceAll() method returns a new string with all occurrences of the searchValue replaced with the replaceValue.

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

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

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

Note that the replaceAll() method was introduced in ECMAScript 2021 and may not be supported in all JavaScript environments. In environments that do not support the replaceAll() method, you can use a regular expression with the global flag g with the replace() method to achieve the same result:

str.replace(/searchValue/g, replaceValue)