From the original SO question How to replace all occurrences of a string in JavaScript?
For example, if I have a string like this:
var str = "Test abc test test abc test test test abc test test abc";
and I do:
str = str.replace('abc', '');
It only removes the first occurrence of abc
, how do I remove all substrings abc
?
Short answer
Use regular expressions (RegExp) with the g parameter, global search
Fragment
Observations
Regular expressions are not trivial since certain characters have an effect on the way the regular expression is interpreted. The processing of these must be applied only to secure strings or they should be escaped before being processed. Here is a more complete example.
Font
Response to How to replace all occurrences of a string in JavaScript?
See also
String.replace() accepts a string or a RegExp object as its first parameter .
If you want to replace all
"abc"
, just use a regular expression with the/g
( global ) modifier, which indicates that all occurrences are replaced.And if you want to ignore case, use the modifier
/i
( ignore case ):General case:
The same can be done in the general case, to replace any substring, and escaping all special characters.
Extending the prototypes of the original types (
built-in prototype
) is not recommended, but in order to show a different solution I am going to give an example of how to do it by modifying the prototype ofString
.Regular expression based implementation
Implementation based on Split and Join (Functional)
It would be used like this:
Note: do not use this method in real code
An alternative to regular expressions can be:
The general pattern is:
This used to, in some cases, be faster than using
protoypes
and regular expressions but that doesn't seem to be the case in modern browsers. Therefore this should only be used as a quick fix to avoid regex escaping but not for actual code that is going to go into production.