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.



Related articles

OnePlus 5T Wallpapers Download

Introduction: The OnePlus 5T is a popular smartphone known for...

Airtel’s First Quarterly Loss in 2002: A Closer Look at Jio’s Impact

The telecom industry has witnessed several significant shifts over...

Xiaomi Confirms Investment in Blackshark Gaming Phone Launch set for April 13

An engaging introduction to Xiaomi Confirms Investment in Blackshark...

LG G7 ThinQ M LCD Panel

Introduction:The LG G7 ThinQ M LCD panel is a...

Intel Core i9 Laptops with Optane Memory

Intel Core i9 laptops with Optane Memory combine the...

Apple iOS 11.4 Beta 1

Apple iOS 11.4 Beta 1 is the latest update...

Google Search AI Reorganization: Improving Search Quality and User Experience

Introduction:In the ever-evolving digital landscape, search engines play a...
Peter Graham
Peter Graham
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.


Please enter your comment!
Please enter your name here