[Solved-5 Solutions] Replace all occurrences of a string in JavaScript - javascript tutorial



Problem:

How to replace all occurrences of a string in JavaScript ?

Solution 1:

Regular Expression Based Implementation

String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};

Split and Join (Functional) Implementation

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};

The regular expression based implementation is the faster, but the split and join an implementation to slower. Regular expression based implementation if search have certain characters they are reserved as special characters in regular expressions.MDN also provides an implementation to escape strings. It is standardized as RegExp.escape(str).

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}

Call escapeRegExp within String.prototype.replaceAll implementation.

Solution 2:

str = str.replace(/abc/g, '');

It response

var find = 'abc';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

Simplify

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}

Note: In regular expressions have a special characters to pass an argument in the find function without any pre-processing it could escape those characters.

function escapeRegExp(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

replaceAll() function is modified to the following and also includes escapeRegExp:

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

Solution 3:

As an alternative to regular expressions is simple to literal string

str = "Test abc test test abc test...".split("abc").join("");

General pattern:

str.split(search).join(replacement)

This code is used to faster than using replaceAll.

Solution 4:

Using g flag set in regular expression to replace all:

someString = 'hello wikitechy;
anotherString = someString.replace(/hello/g, 'welcome to');
// anotherString now contains "welcome to wikitechy"

Solution 5:

Using string prototype function:

String.prototype.replaceAll = function (find, replace) {
    var str = this;
    return str.replace(new RegExp(find, 'g'), replace);
};

We want escape to find the special characters:

String.prototype.replaceAll = function (find, replace) {
    var str = this;
    return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};


Related Searches to javascript tutorial - Replace all occurrences of a string in javaScript