Replace All Occurrences of a String in JavaScript


In this article, let’s discuss about how to replace all the occurrences of a string in a javascript.

To make it generic, Lets define a replaceall method in javascript.

Case sensitive replace all

Following code will replace all occurrences of a string globally using case sensitive pattern.

We are using regular expression to replace a string occurrence globally ‘g’.


String.prototype.replaceAll = function (targetString, subString) {
 var inputString = this;
 inputString = inputString.replace(new RegExp(targetString, 'g'), subString); //replace a string globally and case sensitive

return (inputString);
};

Prototype is a global property which is available with almost all JavaScript objects. It allows you to add properties and methods to an object.

JavaScript prototype Property Syntax:


object.prototype.name=value

Example:


var inputString = "This is aBc. aBC is not a bad start. This is good ABC";

inputString = inputString.replaceAll("aBc", "xyz"); //replace all case sensitive

alert(inputString); //This will print "This is xyz. aBC is not a bad start. This is good ABC"

Case insensitive replace all

We are using regular expression to replace a string occurrence globally and case insensitive which is ‘gi’.


String.prototype.replaceAllCaseInSensitive = function (targetString, subString) {
 var inputString = this;
 inputString = inputString.replace(new RegExp(targetString, 'gi'), subString); //replace a string globally and case-insensitive

return (inputString);
};

Example:


var inputString = "This is aBc. aBC is not a bad start. This is good ABC";

inputString = inputString.replaceAll("abc", "xyz"); //replace all case sensitive

alert(inputString); //This will print "This is xyz. xyz is not a bad start. This is good xyz"

jsFiddle example

Related articles

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s