Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript multiple replace [duplicate]

I have this string in my JavaScript code:

"Test abc test test abc test test test abc test test abc" 

Doing:

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

Seems to only remove the first occurrence of abc in the string above.

How can I replace all occurrences of it?

like image 312
Ali Avatar asked Jul 17 '09 17:07

Ali


People also ask

How do you replace multiple times?

Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.

How do you replace multiple values in a string?

Show activity on this post. var str = "I have a cat, a dog, and a goat."; str = str. replace(/goat/i, "cat"); // now str = "I have a cat, a dog, and a cat." str = str. replace(/dog/i, "goat"); // now str = "I have a cat, a goat, and a cat." str = str.

How do I replace multiple spaces in single space?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.

How do you replace all occurrences of a character in a string in Javascript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.


2 Answers

For the sake of completeness, I got to thinking about which method I should use to do this. There are basically two ways to do this as suggested by the other answers on this page.

Note: In general, extending the built-in prototypes in JavaScript is generally not recommended. I am providing as extensions on the String prototype simply for purposes of illustration, showing different implementations of a hypothetical standard method on the String built-in prototype.


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); }; 

Not knowing too much about how regular expressions work behind the scenes in terms of efficiency, I tended to lean toward the split and join implementation in the past without thinking about performance. When I did wonder which was more efficient, and by what margin, I used it as an excuse to find out.

On my Chrome Windows 8 machine, the regular expression based implementation is the fastest, with the split and join implementation being 53% slower. Meaning the regular expressions are twice as fast for the lorem ipsum input I used.

Check out this benchmark running these two implementations against each other.


As noted in the comment below by @ThomasLeduc and others, there could be an issue with the regular expression-based implementation if search contains certain characters which are reserved as special characters in regular expressions. The implementation assumes that the caller will escape the string beforehand or will only pass strings that are without the characters in the table in Regular Expressions (MDN).

MDN also provides an implementation to escape our strings. It would be nice if this was also standardized as RegExp.escape(str), but alas, it does not exist:

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

We could call escapeRegExp within our String.prototype.replaceAll implementation, however, I'm not sure how much this will affect the performance (potentially even for strings for which the escape is not needed, like all alphanumeric strings).

like image 21
Cory Gross Avatar answered Oct 15 '22 17:10

Cory Gross


As of August 2020: Modern browsers have support for the String.replaceAll() method defined by the ECMAScript 2021 language specification.


For older/legacy browsers:

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

Here is how this answer evolved:

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

In response to comment "what's if 'abc' is passed as a variable?":

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

In response to Click Upvote's comment, you could simplify it even more:

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

Note: Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the find function above without pre-processing it to escape those characters. This is covered in the Mozilla Developer Network's JavaScript Guide on Regular Expressions, where they present the following utility function (which has changed at least twice since this answer was originally written, so make sure to check the MDN site for potential updates):

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

So in order to make the replaceAll() function above safer, it could be modified to the following if you also include escapeRegExp:

function replaceAll(str, find, replace) {   return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } 
like image 75
Sean Bright Avatar answered Oct 15 '22 17:10

Sean Bright