javascript

How to Replace All Occurrences of A Word in Javascript


In this article, you will learn how to replace all occurrences of a word in Javascript.

Let’s say you have a string variable named ‘a’ with value “How much wood would a woodchuck chuck if a woodchuck could chuck wood?”.

var a = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"

In order to replace all occurrences of a word in a string, you can use the replaceAll() method. In this example, you will be replacing all occurrences of the word “wood” into “steel”.

var a = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"

console.log(a.replaceAll("wood", "steel"));

Note: The replaceAll() method functions by replacing all occurrences of the first argument with the second argument.


Share on social media

//