How to Replace All Occurrences of a String?

spot_img

Share This Post

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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Related Posts

6 Best Home Generators

If you live in an area where you experience...

8 Best Portable Workplaces

While most hobbyists, woodworkers, or DIYers enjoy picking the...

How to Choose Best Lift Chair?

For people with physical disabilities and the elderly, getting...

NuWave Brio Air Fryer Review

Craving for some fried goods but scared of the...

Commercial Toaster: Top Picks with Buying Guide and FAQs

Commercial Toaster: Top Picks with Buying Guide and FAQs...

Best SUP Board Leashes

If you’re a paddler, you know how important the...
spot_img
- Advertisement -spot_img