Вы находитесь на странице: 1из 4

In this tutorial, we'll look at a couple of ways to replace all occurrences of a specified

string using JavaScript. For all examples in this tutorial, we'll be using the following
string:

var str = 'hello world! hello people! Hello hello!';


Using JavaScript replace() Function
The JavaScript replace() function takes two arguments:

1. The string or regular expression to search for.

2. The string to replace the matches found with.

Replacing First Match Only:


If we specify the first argument as string, the replace function only replaces the first
occurrence of the string. Consider the example below:
str.replace('hello', 'hi'); // output: hi world! hello people! Hello hello!
The same can be re-written using a regular expression as the first argument, like so:

// method 1: regular expression literal notation — enclosed between slashes

str.replace(/hello/, 'hi');

// method 2: calling the constructor function of the RegExp object

str.replace(new RegExp('hello'), 'hi');

// output: hi world! hello people! Hello hello!


While the literal notation can be a quick shorthand way of writing regular expressions,
calling the constructor function of the RegExp object can be useful if you wish to use a
variable.

If you wish to search for Regular Expressions' reserved characters (i.e. -/\^$*+?.()|[]{}),
they will need to be escaped using a \ (back slash).

Replacing All Matches:


In order to replace all instances of the specified string, we need to use a regular
expression as the first argument of the replace function with a "global" matching flag.
Consider the example below:
// method 1: literal notation

str.replace(/hello/g, 'hi');

// method 2: RegExp object

str.replace(new RegExp('hello', 'g'), 'hi');

// output: hi world! hi people! Hello hi!


The magic happens with the g flag of the regular expression which indicates a global
search and replace.

Replacing All Matches With A Case-Insensitive Search:


In the previous example, you may have noticed that the regular expression search and
replace is case-sensitive. We can make it case-insensitive by adding the i flag after the
global flag, like so:

// method 1: literal notation

str.replace(/hello/gi, 'hi');

// method 2: RegExp object

str.replace(new RegExp('hello', 'gi'), 'hi');

// output: hi world! hi people! hi hi!

Using The split() And join() JavaScript Functions


The JavaScript split function splits a string into an array based on a string (or regular
expression), while the join function joins an array into a string. The joinfunction takes
as argument an optional string which can be used to join elements of array.

Replacing All Matches With A Case-Sensitive Search:


str.split('hello').join('hi'); // output: hi world! hi people! Hello hi!
As you can see from the output of the example, this method does a case-sensitive
search and replace.
Replacing All Matches With A Case-Insensitive Search:
// method 1: regular expression literal notation — enclosed between slashes

str.split(/hello/i).join('hi');

// method 2: calling the constructor function of the RegExp object

str.split(new RegExp('hello', 'i')).join('hi');

// output: hi world! hi people! hi hi!

Doing A Custom Recursirve Search & Replace


As mentioned earlier in this article, when we supply string as the first argument of
the replace function, it replaces only the first occurrence of the string. Using that
information we can create a function that recursively goes through the entire string
searching and replacing till all matches are replaced.

Replacing All Matches With A Case-Sensitive Search:


String.prototype.replaceAll = function(searchStr, replaceStr) {

var str = this;

// no match exists in string?

if(str.indexOf(searchStr) === -1) {

// return string

return str;

// replace and remove first match, and do another recursirve search/replace

return (str.replace(searchStr, replaceStr)).replaceAll(searchStr,

replaceStr);

}
// usage:

str.replaceAll('hello', 'hi');

// output: hi world! hi people! Hello hi!

Replacing All Matches With A Case-Insensitive Search:


Since case-insensitive searches are easy with regular expressions, we can simply use
regular expression with a gi flag. So, there is no real need to do a recursive search and
replace in this instance.
String.prototype.replaceAll = function(searchStr, replaceStr) {

var str = this;

// escape regexp special characters in search string

searchStr = searchStr.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

return str.replace(new RegExp(searchStr, 'gi'), replaceStr);

};

// usage:

str.replaceAll('hello', 'hi');

// output: hi world! hi people! hi hi!

Вам также может понравиться