Let’s says we have a 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.
“This a String. This the Best String.”
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.
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.