When working with JavaScript, you may need to find and replace all instances of a string within another string. We are lucky that JavaScript has some clean answers to this problem.
The Problem
Let’s says we have a string.
Input String
“This is a String. This is the Best String.”
We want to take this string and remove all instances of “is” from our string. Here is our intended output.
Output String
“This a String. This the Best String.”
Solution #1
We can use the new replaceAll string prototype in new browsers. With this method, we get a clean, one-line answer.
The first parameter is the part of the string you want to find, and the second is what you want to replace it with.
var str = "This is a String. This is the Best String.";
var answer = str.replaceAll(" is","")
Be careful. This code doesn’t look at each word on its own. So your substring will be changed if it is part of a word. In that case, make sure to put spaces between the words, as shown above.
Solution #2
Using the replace string prototype with a regex expression is another solution that will work on most browsers.
The first parameter is the regular expression to use to find all of your substring’s occurrences. We use the g modifier to make sure we get all the matches. With the second parameter, we tell the program what to put in place of the string.
var str = "This is a String. This is the Best String.";
var answer = str.replace(/ is/g,"")
So, there are two easy ways to find and change all instances of a string in another string.