From this tutorial, beginners or experienced programmers can easily gain complete knowledge on how to replace all occurrences of a string in javascript. Make use of these available direct links and directly jump into the respective stuff related to the Javascript program related to all Occurrences of a String.
- How to Replace all Occurrences of a String in JavaScript?
- Using a Regular Expression (RegEx)
- Using JavaScript Split() and Join() method
How to Replace all Occurrences of a String in JavaScript?
There are two proper ways to replace all occurrences of a string in JavaScript. Below, we have described them neatly including an example program. Okay, Let’s have a look at these methods and learn the javascript program to replace all occurrences of a string.
- Using a Regular Expression (RegEx)
- Using JavaScript Split() and Join() method
Using a Regular Expression (RegEx)
String.replace(/<TERM>/g, '')
This works as a case sensitive substitution.
For example,
const phrase = "I love my dog! Dogs are great"; const stripped = phrase.replace(/dog/g, ""); console.log(stripped);
The output would be
I love my ! Dogs are great
To perform a case insensitive replacement, use the i
option,
const phrase = "I love my dog! Dogs are great"; const stripped = phrase.replace(/dog/gi, ""); console.log(stripped);
The output would be
I love my ! s are great
NOTE: Remember that if the string contains some special characters, it won’t play well with regular expressions, so the suggestion is to escape the string using this function.
Do Check:
Using JavaScript Split() and Join() method
An alternative solution, albeit slower than the regex, is using two JavaScript functions.
The first is split()
, which truncates a string when it finds a pattern (case sensitive), and returns an array with the tokens:
const phrase = "I love my dog! Dogs are great"; const tokens = phrase.split("dog").join(); console.log(tokens);
The final output would however be the same. (case sensitive)
I love my ! Dogs are great