How to Replace All Occurrences of a String?

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.

spot_img

Subscribe

Related articles

How to get million views on youtube?

To get a million views on YouTube, you will...

Can I create a custom dashboard in react?

Yes, you can create a custom dashboard in React....

All You Need to Know About Xbox 360 Backward Compatibility

The Xbox 360 works well with some games that...

How to Check if an Array has More than One Element in PHP?

An array is a group of data structures. In...

Learn How to Select All in VIM?

Now is the time to improve your VIM skills...
spot_img
Peter Graham
Peter Grahamhttps://fix-iphones.com
Hi there! I'm Peter, a software engineer and tech enthusiast with over 10 years of experience in the field. I have a passion for sharing my knowledge and helping others understand the latest developments in the tech world. When I'm not coding, you can find me hiking or trying out the latest gadgets.

LEAVE A REPLY

Please enter your comment!
Please enter your name here