Given a string:
s = "Test abc test test abc test test test abc test test abc";
This seems to only remove the first occurrence of abc in the string above:
s = s.replace('abc', '');
How do I replace all occurrences of it?
Given a string:
s = "Test abc test test abc test test test abc test test abc";
This seems to only remove the first occurrence of abc in the string above:
s = s.replace('abc', '');
How do I replace all occurrences of it?
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);
}
In the latest versions of most popular browsers, you can use replaceAll
as shown here:
let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"
But check Can I use or another compatibility table first to make sure the browsers you're targeting have added support for it first.
For Node.js and compatibility with older/non-current browsers:
Note: Don't use the following solution in performance critical code.
As an alternative to regular expressions for a simple literal string, you could use
str = "Test abc test test abc test...".split("abc").join("");
The general pattern is
str.split(search).join(replacement)
This used to be faster in some cases than using replaceAll and a regular expression, but that doesn't seem to be the case anymore in modern browsers.
Benchmark: https://jsben.ch/TZYzj
If you have a performance-critical use case (e.g., processing hundreds of strings), use the regular expression method. But for most typical use cases, this is well worth not having to worry about special characters.
Using a regular expression with the g flag set will replace all:
someString = 'the cat looks like a cat';
anotherString = someString.replace(/cat/g, 'dog');
// anotherString now contains "the dog looks like a dog"
These are the most common and readable methods.
var str = "Test abc test test abc test test test abc test test abc"
Method 1:
str = str.replace(/abc/g, "replaced text");
Method 2:
str = str.split("abc").join("replaced text");
Method 3:
str = str.replace(new RegExp("abc", "g"), "replaced text");
Method 4:
while(str.includes("abc")){
str = str.replace("abc", "replaced text");
}
Output:
console.log(str);
// Test replaced text test test replaced text test test test replaced text test test replaced text
Match against a global regular expression:
anotherString = someString.replace(/cat/g, 'dog');
For replacing a single time, use:
var res = str.replace('abc', "");
For replacing multiple times, use:
var res = str.replace(/abc/g, "");
str = str.replace(/abc/g, '');
Or try the replaceAll method, as recommended in this answer:
str = str.replaceAll('abc', '');
or:
var search = 'abc';
str = str.replaceAll(search, '');
EDIT: Clarification about replaceAll availability
The replaceAll method is added to String's prototype. This means it will be available for all string objects/literals.
Example:
var output = "test this".replaceAll('this', 'that'); // output is 'test that'.
output = output.replaceAll('that', 'this'); // output is 'test this'
Today 27.12.2019 I perform tests on macOS v10.13.6 (High Sierra) for the chosen solutions.
Conclusions
str.replace(/abc/g, ''); (C) is a good cross-browser fast solution for all strings.split-join (A,B) or replace (C,D) are fastwhile (E,F,G,H) are slow - usually ~4 times slower for small strings and about ~3000 times (!) slower for long stringsI also create my own solution. It looks like currently it is the shortest one which does the question job:
str.split`abc`.join``
str = "Test abc test test abc test test test abc test test abc";
str = str.split`abc`.join``
console.log(str);
The tests were performed on Chrome 79.0, Safari 13.0.4 and Firefox 71.0 (64 bit). The tests RA and RB use recursion. Results
You can run tests on your machine HERE. Results for Chrome:
The recursive solutions RA and RB gives
RangeError: Maximum call stack size exceeded
For 1M characters they even break Chrome
I try to perform tests for 1M characters for other solutions, but E,F,G,H takes so much time that browser ask me to break script so I shrink test string to 275K characters. You can run tests on your machine HERE. Results for Chrome
Code used in tests
var t="Test abc test test abc test test test abc test test abc"; // .repeat(5000)
var log = (version,result) => console.log(`${version}: ${result}`);
function A(str) {
return str.split('abc').join('');
}
function B(str) {
return str.split`abc`.join``; // my proposition
}
function C(str) {
return str.replace(/abc/g, '');
}
function D(str) {
return str.replace(new RegExp("abc", "g"), '');
}
function E(str) {
while (str.indexOf('abc') !== -1) { str = str.replace('abc', ''); }
return str;
}
function F(str) {
while (str.indexOf('abc') !== -1) { str = str.replace(/abc/, ''); }
return str;
}
function G(str) {
while(str.includes("abc")) { str = str.replace('abc', ''); }
return str;
}
// src: https://stackoverflow.com/a/56989553/860099
function H(str)
{
let i = -1
let find = 'abc';
let newToken = '';
if (!str)
{
if ((str == null) && (find == null)) return newToken;
return str;
}
while ((
i = str.indexOf(
find, i >= 0 ? i + newToken.length : 0
)) !== -1
)
{
str = str.substring(0, i) +
newToken +
str.substring(i + find.length);
}
return str;
}
// src: https://stackoverflow.com/a/22870785/860099
function RA(string, prevstring) {
var omit = 'abc';
var place = '';
if (prevstring && string === prevstring)
return string;
prevstring = string.replace(omit, place);
return RA(prevstring, string)
}
// src: https://stackoverflow.com/a/26107132/860099
function RB(str) {
var find = 'abc';
var replace = '';
var i = str.indexOf(find);
if (i > -1){
str = str.replace(find, replace);
i = i + replace.length;
var st2 = str.substring(i);
if(st2.indexOf(find) > -1){
str = str.substring(0,i) + RB(st2, find, replace);
}
}
return str;
}
log('A ', A(t));
log('B ', B(t));
log('C ', C(t));
log('D ', D(t));
log('E ', E(t));
log('F ', F(t));
log('G ', G(t));
log('H ', H(t));
log('RA', RA(t)); // use reccurence
log('RB', RB(t)); // use reccurence
<p style="color:red">This snippet only presents codes used in tests. It not perform test itself!<p>
String.prototype.replaceAll - ECMAScript 2021
The new String.prototype.replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be either a string or a RegExp, and the replacement can be either a string or a function to be called for each match.
const message = 'dog barks meow meow';
const messageFormatted = message.replaceAll('meow', 'woof')
console.log(messageFormatted);
The simplest way to do this without using any regular expression is split and join, like the code here:
var str = "Test abc test test abc test test test abc test test abc";
console.log(str.split('abc').join(''));
If the string contains a similar pattern like abccc, you can use this:
str.replace(/abc(\s|$)/g, "")
As of August 2020 there is a Stage 4 proposal to ECMAScript that adds the replaceAll method to String.
It's now supported in Chrome 85+, Edge 85+, Firefox 77+, Safari 13.1+.
The usage is the same as the replace method:
String.prototype.replaceAll(searchValue, replaceValue)
Here's an example usage:
'Test abc test test abc test.'.replaceAll('abc', 'foo'); // -> 'Test foo test test foo test.'
It's supported in most modern browsers, but there exist polyfills:
It is supported in the V8 engine behind an experimental flag --harmony-string-replaceall.
Read more on the V8 website.
The previous answers are way too complicated. Just use the replace function like this:
str.replace(/your_regex_pattern/g, replacement_string);
Example:
var str = "Test abc test test abc test test test abc test test abc";
var res = str.replace(/[abc]+/g, "");
console.log(res);
After several trials and a lot of fails, I found that the below function seems to be the best all-rounder when it comes to browser compatibility and ease of use. This is the only working solution for older browsers that I found. (Yes, even though old browser are discouraged and outdated, some legacy applications still make heavy use of OLE browsers (such as old Visual Basic 6 applications or Excel .xlsm macros with forms.)
Anyway, here's the simple function.
function replaceAll(str, match, replacement){
return str.split(match).join(replacement);
}
Check this answer. Maybe it will help, and I used it in my project.
function replaceAll(searchString, replaceString, str) {
return str.split(searchString).join(replaceString);
}
replaceAll('abc', '',"Test abc test test abc test test test abc test test abc" ); // "Test test test test test test test test "
With the regular expression i flag for case insensitive
console.log('App started'.replace(/a/g, '')) // Result: "App strted"
console.log('App started'.replace(/a/gi, '')) // Result: "pp strted"
Method 1
Try to implement a regular expression:
"Test abc test test abc test test test abc test test abc".replace(/\abc/g, ' ');
Method 2
Split and join. Split with abc and join with empty space.
"Test abc test test abc test test test abc test test abc".split("abc").join(" ")
This can be achieved using regular expressions. A few combinations that might help someone:
var word = "this,\\ .is*a*test, '.and? / only / 'a \ test?";
var stri = "This is a test and only a test";
To replace all non alpha characters,
console.log(word.replace(/([^a-z])/g,' ').replace(/ +/g, ' '));
Result: [this is a test and only a test]
To replace multiple continuous spaces with one space,
console.log(stri.replace(/ +/g,' '));
Result: [This is a test and only a test]
To replace all * characters,
console.log(word.replace(/\*/g,''));
Result: [this,\ .isatest, '.and? / only / 'a test?]
To replace question marks (?)
console.log(word.replace(/\?/g,'#'));
Result: [this,\ .is*a*test, '.and# / only / 'a test#]
To replace quotation marks,
console.log(word.replace(/'/g,'#'));
Result: [this,\ .is*a*test, #.and? / only / #a test?]
To replace all ' characters,
console.log(word.replace(/,/g,''));
Result: [this\ .is*a*test '.and? / only / 'a test?]
To replace a specific word,
console.log(word.replace(/test/g,''));
Result: [this,\ .is*a*, '.and? / only / 'a ?]
To replace backslash,
console.log(word.replace(/\\/g,''));
Result: [this, .is*a*test, '.and? / only / 'a test?]
To replace forward slash,
console.log(word.replace(/\//g,''));
Result: [this,\ .is*a*test, '.and? only 'a test?]
To replace all spaces,
console.log(word.replace(/ /g,'#'));
Result: [this,\#.is*a*test,####'.and?#/#only#/#####'a##test?]
To replace dots,
console.log(word.replace(/\./g,'#'));
Result: [this,\ #is*a*test, '#and? / only / 'a test?]
I use split and join or this function:
function replaceAll(text, busca, reemplaza) {
while (text.toString().indexOf(busca) != -1)
text = text.toString().replace(busca, reemplaza);
return text;
}
Of course in 2021 the right answer is:
console.log(
'Change this and this for me'.replaceAll('this','that') // Normal case
);
console.log(
'aaaaaa'.replaceAll('aa','a') // Challenged case
);
If you don't want to deal with replace() + RegExp.
But what if the browser is from before 2020?
In this case we need polyfill (forcing older browsers to support new features) (I think for a few years will be necessary). I could not find a completely right method in answers. So I suggest this function that will be defined as a polyfill.
replaceAll polyfill:replaceAll polyfill (with global-flag error) (more principled version)if (!String.prototype.replaceAll) { // Check if the native function not exist
Object.defineProperty(String.prototype, 'replaceAll', { // Define replaceAll as a prototype for (Mother/Any) String
configurable: true, writable: true, enumerable: false, // Editable & non-enumerable property (As it should be)
value: function(search, replace) { // Set the function by closest input names (For good info in consoles)
return this.replace( // Using native String.prototype.replace()
Object.prototype.toString.call(search) === '[object RegExp]' // IsRegExp?
? search.global // Is the RegEx global?
? search // So pass it
: function(){throw new TypeError('replaceAll called with a non-global RegExp argument')}() // If not throw an error
: RegExp(String(search).replace(/[.^$*+?()[{|\\]/g, "\\$&"), "g"), // Replace all reserved characters with '\' then make a global 'g' RegExp
replace); // passing second argument
}
});
}
replaceAll polyfill (With handling global-flag missing by itself) (my first preference) - Why?if (!String.prototype.replaceAll) { // Check if the native function not exist
Object.defineProperty(String.prototype, 'replaceAll', { // Define replaceAll as a prototype for (Mother/Any) String
configurable: true, writable: true, enumerable: false, // Editable & non-enumerable property (As it should be)
value: function(search, replace) { // Set the function by closest input names (For good info in consoles)
return this.replace( // Using native String.prototype.replace()
Object.prototype.toString.call(search) === '[object RegExp]' // IsRegExp?
? search.global // Is the RegEx global?
? search // So pass it
: RegExp(search.source, /\/([a-z]*)$/.exec(search.toString())[1] + 'g') // If not, make a global clone from the RegEx
: RegExp(String(search).replace(/[.^$*+?()[{|\\]/g, "\\$&"), "g"), // Replace all reserved characters with '\' then make a global 'g' RegExp
replace); // passing second argument
}
});
}
if(!String.prototype.replaceAll){Object.defineProperty(String.prototype,'replaceAll',{configurable:!0,writable:!0,enumerable:!1,value:function(search,replace){return this.replace(Object.prototype.toString.call(search)==='[object RegExp]'?search.global?search:RegExp(search.source,/\/([a-z]*)$/.exec(search.toString())[1]+'g'):RegExp(String(search).replace(/[.^$*+?()[{|\\]/g,"\\$&"),"g"),replace)}})}
if(!String.prototype.replaceAll){Object.defineProperty(String.prototype,'replaceAll',{configurable:!0,writable:!0,enumerable:!1,value:function(search,replace){return this.replace(Object.prototype.toString.call(search)==='[object RegExp]'?search.global?search:RegExp(search.source,/\/([a-z]*)$/.exec(search.toString())[1]+'g'):RegExp(String(search).replace(/[.^$*+?()[{|\\]/g,"\\$&"),"g"),replace)}})}
console.log(
'Change this and this for me'.replaceAll('this','that')
); // Change that and that for me
console.log(
'aaaaaa'.replaceAll('aa','a')
); // aaa
console.log(
'{} (*) (*) (RegEx) (*) (\*) (\\*) [reserved characters]'.replaceAll('(*)','X')
); // {} X X (RegEx) X X (\*) [reserved characters]
console.log(
'How (replace) (XX) with $1?'.replaceAll(/(xx)/gi,'$$1')
); // How (replace) ($1) with $1?
console.log(
'Here is some numbers 1234567890 1000000 123123.'.replaceAll(/\d+/g,'***')
); // Here is some numbers *** *** *** and need to be replaced.
console.log(
'Remove numbers under 233: 236 229 711 200 5'.replaceAll(/\d+/g, function(m) {
return parseFloat(m) < 233 ? '' : m
})
); // Remove numbers under 233: 236 711
console.log(
'null'.replaceAll(null,'x')
); // x
// The difference between My first preference and the original:
// Now in 2022 with browsers > 2020 it should throw an error (But possible it be changed in future)
// console.log(
// 'xyz ABC abc ABC abc xyz'.replaceAll(/abc/i,'')
// );
// Browsers < 2020:
// xyz xyz
// Browsers > 2020
// TypeError: String.prototype.replaceAll called with a non-global RegExp
The result is the same as the native replaceAll in case of the first argument input is:
null, undefined, Object, Function, Date, ... , RegExp, Number, String, ...
Ref: 22.1.3.19 String.prototype.replaceAll ( searchValue, replaceValue) + RegExp Syntax
Important note: As some professionals mention it, many of recursive functions that suggested in answers, will return the wrong result. (Try them with the challenged case of the above snippet.)
Maybe some tricky methods like .split('searchValue').join('replaceValue') or some well managed functions give same result, but definitely with much lower performance than native replaceAll() / polyfill replaceAll() / replace() + RegExp
For example, we can support IE7+ too, by not using Object.defineProperty() and using my old naive assignment method:
if (!String.prototype.replaceAll) {
String.prototype.replaceAll = function(search, replace) { // <-- Naive method for assignment
// ... (Polyfill code Here)
}
}
And it should work well for basic uses on IE7+.
But as here @sebastian-simon explained about, that can make secondary problems in case of more advanced uses. E.g.:
for (var k in 'hi') console.log(k);
// 0
// 1
// replaceAll <-- ?
In fact, my suggested option is a little optimistic. Like we trusted the environment (browser and Node.js), it is definitely for around 2012-2021. Also it is a standard/famous one, so it does not require any special consideration.
But there can be even older browsers or some unexpected problems, and polyfills still can support and solve more possible environment problems. So in case we need the maximum support that is possible, we can use polyfill libraries like:
Specially for replaceAll:
<script src="https://polyfill.io/v3/polyfill.min.js?features=String.prototype.replaceAll"></script>
In terms of performance related to the main answers, these are some online tests.
While the following are some performance tests using console.time() (they work best in your own console, and the time is very short to be seen in the snippet).
console.time('split and join');
"javascript-test-find-and-replace-all".split('-').join(' ');
console.timeEnd('split and join')
console.time('regular expression');
"javascript-test-find-and-replace-all".replace(new RegExp('-', 'g'), ' ');
console.timeEnd('regular expression');
console.time('while');
let str1 = "javascript-test-find-and-replace-all";
while (str1.indexOf('-') !== -1) {
str1 = str1.replace('-', ' ');
}
console.timeEnd('while');
The interesting thing to notice is that if you run them multiple times, the results are always different even though the regular expression solution seems the fastest on average and the while loop solution the slowest.
There is now a finished proposal for integrating String.prototype.replaceAll into the official specification. Eventually, developers will not have to come up with their own implementations for replaceAll - instead, modern JavaScript engines will support it natively.
The proposal is at stage 4, which means that everything is complete, and all that's left is for browsers to start implementing it.
It has shipped in the latest versions of Chrome, Firefox, and Safari.
Here are the implementation details:
Per the current TC39 consensus,
String.prototype.replaceAllbehaves identically toString.prototype.replacein all cases, except for the following two cases:
- If
searchValueis a string,String.prototype.replaceonly replaces a single occurrence of thesearchValue, whereasString.prototype.replaceAllreplaces all occurrences of thesearchValue(as if.split(searchValue).join(replaceValue)or a global & properly-escaped regular expression had been used).- If
searchValueis a non-global regular expression,String.prototype.replacereplaces a single match, whereasString.prototype.replaceAllthrows an exception. This is done to avoid the inherent confusion between the lack of a global flag (which implies "do NOT replace all") and the name of the method being called (which strongly suggests "replace all").Notably,
String.prototype.replaceAllbehaves just likeString.prototype.replaceifsearchValueis a global regular expression.
You can see a specification-compliant polyfill here.
In supported environments, the following snippet will log foo-bar-baz, without throwing an error:
const str = 'foo bar baz';
console.log(
str.replaceAll(' ', '-')
);
Here's a very simple solution. You can assign a new method to a String object
String.prototype.replaceAll = function(search, replace){
return this.replace(new RegExp(search, 'g'), replace)
}
var str = "Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');
console.log(str) // -> Test test test test test test test test
str = "Test abc test test abc test test test abc test test abc"
str.split(' ').join().replace(/abc/g,'').replace(/,/g, ' ')
In November 2019, a new feature is added to the JavaScript, string.prototype.replaceAll().
Currently it's only supported with Babel, but maybe in the future it can be implemented in all the browsers. For more information, read here.
This can be solved using regular expressions and the flag g, which means to not stop after finding the first match. Really, regular expressions are life savers!
function replaceAll(string, pattern, replacement) {
return string.replace(new RegExp(pattern, "g"), replacement);
}
// or if you want myString.replaceAll("abc", "");
String.prototype.replaceAll = function(pattern, replacement) {
return this.replace(new RegExp(pattern, "g"), replacement);
};
I just want to share my solution, based on some of the functional features of last versions of JavaScript:
var str = "Test abc test test abc test test test abc test test abc";
var result = str.split(' ').reduce((a, b) => {
return b == 'abc' ? a : a + ' ' + b; })
console.warn(result)
The best solution, in order to replace any character we use the indexOf(), includes(), and substring() functions to replace the matched string with the provided string in the current string.
String.indexOf() function is to find the nth match index position.String.includes() method determines whether one string may be found within another string, returning true or false as appropriate.String.substring() function is to get the parts of String(preceding,exceding). Add the replace String in-between these parts to generate final return String.The following function allows to use any character.
where as RegExp will not allow some special character like ** and some characters need to be escaped, like $.
String.prototype.replaceAllMatches = function(obj) { // Obj format: { 'matchkey' : 'replaceStr' }
var retStr = this;
for (var x in obj) {
//var matchArray = retStr.match(new RegExp(x, 'ig'));
//for (var i = 0; i < matchArray.length; i++) {
var prevIndex = retStr.indexOf(x); // matchkey = '*', replaceStr = '$*' While loop never ends.
while (retStr.includes(x)) {
retStr = retStr.replaceMatch(x, obj[x], 0);
var replaceIndex = retStr.indexOf(x);
if( replaceIndex < prevIndex + (obj[x]).length) {
break;
} else {
prevIndex = replaceIndex;
}
}
}
return retStr;
};
String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
var retStr = this, repeatedIndex = 0;
//var matchArray = retStr.match(new RegExp(matchkey, 'ig'));
//for (var x = 0; x < matchArray.length; x++) {
for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
if (repeatedIndex == 0 && x == 0) {
repeatedIndex = retStr.indexOf(matchkey);
} else { // matchIndex > 0
repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
}
if (x == matchIndex) {
retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
matchkey = null; // To break the loop.
}
}
return retStr;
};
We can also use the regular expression object for matching text with a pattern. The following are functions which will use the regular expression object.
You will get SyntaxError when you are using an invalid regular expression pattern like '**'.
String.replace() function is used to replace the specified String with the given String.String.match() function is to find how many time the string is repeated.RegExp.prototype.test method executes a search for a match between a regular expression and a specified string. Returns true or false.String.prototype.replaceAllRegexMatches = function(obj) { // Obj format: { 'matchkey' : 'replaceStr' }
var retStr = this;
for (var x in obj) {
retStr = retStr.replace(new RegExp(x, 'ig'), obj[x]);
}
return retStr;
};
Note that regular expressions are written without quotes.
Examples to use the above functions:
var str = "yash yas $dfdas.**";
console.log('String: ', str);
// No need to escape any special character
console.log('Index matched replace: ', str.replaceMatch('as', '*', 2));
console.log('Index Matched replace: ', str.replaceMatch('y', '~', 1));
console.log('All Matched replace: ', str.replaceAllMatches({'as': '**', 'y':'Y', '$':'-'}));
console.log('All Matched replace : ', str.replaceAllMatches({'**': '~~', '$':'&$&', '&':'%', '~':'>'}));
// You need to escape some special Characters
console.log('REGEX all matched replace: ', str.replaceAllRegexMatches({'as' : '**', 'y':'Y', '\\$':'-'}));
Result:
String: yash yas $dfdas.**
Index Matched replace: yash yas $dfd*.**
Index Matched replace: yash ~as $dfdas.**
All Matched replace: Y**h Y** -dfd**.**
All Matched replace: yash yas %$%dfdas.>>
REGEX All Matched replace: Y**h Y** -dfd**.**
This should work.
String.prototype.replaceAll = function (search, replacement) {
var str1 = this.replace(search, replacement);
var str2 = this;
while(str1 != str2) {
str2 = str1;
str1 = str1.replace(search, replacement);
}
return str1;
}
Example:
Console.log("Steve is the best character in Minecraft".replaceAll("Steve", "Alex"));
var str = "Test abc test test abc test test test abc test test abc";
var replaced_str = str.split('abc').join('');
console.log(replaced_str);
This solution combines some previous answers and conforms somewhat better to the proposed August 2020 standard solution. This solution is still viable for me in September 2020, as String.replaceAll is not available in the Node.js binary I am using.
RegExp.escape is a separate issue to deal with, but it is important here, because the official proposed solution will automatically escape string-based find input. This String.replaceAll polyfill would not without the RegExp.escape logic.
I have added an answer which doesn't polyfill RegExp.Escape, in the case that you don't want that.
If you pass a regular expression to find, you must include g as a flag. This polyfill won't provide a nice TypeError for you and will cause you a major bad time.
If you need exact standards conformance, for an application which is rigorously relying on the standard implementation, then I suggest using Babel or some other tool to get you the 'right answer' every time instead of Stack Overflow. That way you won't have any surprises.
Code:
if (!Object.prototype.hasOwnProperty.call(RegExp, 'escape')) {
RegExp.escape = function(string) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
// https://github.com/benjamingr/RegExp.escape/issues/37
return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
};
}
if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {
String.prototype.replaceAll = function(find, replace) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
// If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.
// TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.
// String parameters to 'find' do not require special handling.
// Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace
// Does not conform to "Specifying a function as a parameter" for replace
return this.replace(
Object.prototype.toString.call(find) == '[object RegExp]' ?
find :
new RegExp(RegExp.escape(find), 'g'),
replace
);
}
}
Code, Minified:
Object.prototype.hasOwnProperty.call(RegExp,"escape")||(RegExp.escape=function(e){return e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}),Object.prototype.hasOwnProperty.call(String,"replaceAll")||(String.prototype.replaceAll=function(e,t){return this.replace("[object RegExp]"==Object.prototype.toString.call(e)?e:new RegExp(RegExp.escape(e),"g"),t)});
Example:
console.log(
't*.STVAL'
.replaceAll(
new RegExp(RegExp.escape('T*.ST'), 'ig'),
'TEST'
)
);
console.log(
't*.STVAL'
.replaceAll(
't*.ST',
'TEST'
);
);
Code without RegExp.Escape:
if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {
String.prototype.replaceAll = function(find, replace) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
// If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.
// TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.
// String parameters to 'find' do not require special handling.
// Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace
// Does not conform to "Specifying a function as a parameter" for replace
return this.replace(
Object.prototype.toString.call(find) == '[object RegExp]' ?
find :
new RegExp(find.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'), 'g'),
replace
);
}
}
Code without RegExp.Escape, Minified:
Object.prototype.hasOwnProperty.call(String,"replaceAll")||(String.prototype.replaceAll=function(e,t){return this.replace("[object RegExp]"==Object.prototype.toString.call(e)?e:new RegExp(e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&"),"g"),t)});
JavaScript provides a direct way to replace a part of a string with another string and there are some tricks also by which you can do this.
To replace all the occurrences you can use replace() or replaceAll method in JavaScript.
replace() method - To replace all elements using this method use a regular expression as a pattern to find the matching string and then replace it with a new string. Please consider using the /g flag with it.const str = "To do or not to do";
const pattern = /do/g;
const replaceBy = "Code";
console.log(str.replace(pattern, replaceBy));
replaceAll() method - To replace all elements using this method, use either a string or regular expression as a pattern to find the matching string and then replace it with a new string. We must use the /g flag with a regular expression in the replaceAll method.const str = "To do or not to do";
const pattern = "do";
const replaceBy = "Code";
console.log(str.replaceAll(pattern, replaceBy));
const pattern2 = /do/g;
console.log(str.replaceAll(pattern2, replaceBy));
Alternate method: By using split and join method
Split the string at what you want to replace and join by using the new string as a separator. See the example.
const str = "To do or not to do";
const newStr = str.split("do").join("Code");
console.log(newStr);
The simplest solution -
let str = "Test abc test test abc test test test abc test test abc";
str = str.split(" ");
str = str.filter((ele, key)=> ele!=="abc")
str = str.join(" ")
Or simply -
str = str.split(" ").filter((ele, key) => ele != "abc").join(" ")
var myName = 'r//i//n//o//l////d';
var myValidName = myName.replace(new RegExp('\//', 'g'), ''); > // rinold
console.log(myValidName);
var myPetName = 'manidog';
var renameManiToJack = myPetName.replace(new RegExp('mani', 'g'), 'jack'); > // jackdog
You can do it without Regex, but you need to be careful if the replacement text contains the search text.
e.g.
replaceAll("nihIaohi", "hI", "hIcIaO", true)
So here is a proper variant of replaceAll, including string-prototype:
function replaceAll(str, find, newToken, ignoreCase)
{
let i = -1;
if (!str)
{
// Instead of throwing, act as COALESCE if find == null/empty and str == null
if ((str == null) && (find == null))
return newToken;
return str;
}
if (!find) // sanity check
return str;
ignoreCase = ignoreCase || false;
find = ignoreCase ? find.toLowerCase() : find;
while ((
i = (ignoreCase ? str.toLowerCase() : str).indexOf(
find, i >= 0 ? i + newToken.length : 0
)) !== -1
)
{
str = str.substring(0, i) +
newToken +
str.substring(i + find.length);
} // Whend
return str;
}
Or, if you want to have a string-prototype function:
String.prototype.replaceAll = function (find, replace) {
let str = this;
let i = -1;
if (!str)
{
// Instead of throwing, act as COALESCE if find == null/empty and str == null
if ((str == null) && (find == null))
return newToken;
return str;
}
if (!find) // sanity check
return str;
ignoreCase = ignoreCase || false;
find = ignoreCase ? find.toLowerCase() : find;
while ((
i = (ignoreCase ? str.toLowerCase() : str).indexOf(
find, i >= 0 ? i + newToken.length : 0
)) !== -1
)
{
str = str.substring(0, i) +
newToken +
str.substring(i + find.length);
} // Whend
return str;
};
In August 2020
No more regular expression stuff
const str = "Test abc test test abc test test test abc test test abc";
const modifiedStr = str.replaceAll('abc', '');
console.log(modifiedStr);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
// Try this way
const str = "Test abc test test abc test test test abc test test abc";
const result = str.split('abc').join('');
console.log(result);
Repeat until you have replaced them all:
const regex = /^>.*/im;
while (regex.test(cadena)) {
cadena = cadena.replace(regex, '*');
}
You can try like this:
Example data:
var text = "heloo,hai,hei"
text = text.replace(/[,]+/g, '')
or
text.forEach((value) => {
hasil = hasil.replace(',', '')
})
All the answers are accepted, and you can do this by many ways. One of the trick to do this is this:
const str = "Test abc test test abc test test test abc test test abc";
const compare = "abc";
arrayStr = str.split(" ");
arrayStr.forEach((element, index) => {
if (element == compare) {
arrayStr.splice(index, 1);
}
});
const newString = arrayStr.join(" ");
console.log(newString);
We can use the replace method in JavaScript:
var result = yourString.replace('regexPattern', "replaceString");
var str = "Test abc test test abc test test test abc test test abc";
var expectedString = str.replace(/abc(\s|$)/g, "");
console.log(expectedString);
I know this isn’t the best way to do this, but you can try this:
var annoyingString = "Test abc test test abc test test test abc test test abc";
while (annoyingString.includes("abc")) {
annoyingString = annoyingString.replace("abc", "")
}
I added the function below to this performance test page in the "library" section:
function _replace(t, s, r){
var i = t.indexOf(s);
if (i == -1) return t;
return t.slice(0, i) + r + _replace(t.slice(i + s.length, t.length), s,r);
}
..and put this in as the test:
var replaced = _replace(testString, 'abc', '123');
.. and that function performs about 34% faster for me than split or regex. The idea / hope was to end up pasting smaller and smaller pieces of the string onto the stack and then building the entire result by unrolling the stack, thereby minimizing extra string copies and extra searches through the same string data and hopefully optimizing use of the CPU cache.
Part of the thought was that if the string isn't too big, it may end up in the CPU cache; passing it and pasting pieces of it puts those bits into the cache, and then the searching can operate entirely using CPU cached data. Now whether or not that's actually what ends up happening I'm sure is entirely JavaScript implementation-dependent.
This isn't as fast as possible, but it's as fast as I could manage without mutable strings. Arrays in JavaScript probably have a pointer for each element, so, a solution involving a lot of array elements is not likely to be as CPU cache friendly as this.
Starting from v85, Chrome now supports String.prototype.replaceAll natively. Note this outperform all other proposed solutions and should be used once majorly supported.
Feature status: https://chromestatus.com/feature/6040389083463680
var s = "hello hello world";
s = s.replaceAll("hello", ""); // s is now "world"
console.log(s)
There is a way to use the new replaceAll() method.
But you need to use a cutting-edge browser or a JavaScript run time environment.
You can check the browser compatibility in here.
I have read this question and answers, but I didn't find an appropriate solution for me. Although the answers are quite useful, I decided to create my own solution from scratch. The problems about this kind of replacing are:
So, I was writing functions to highlight search results in a table, where table data cells may have links inside, as well as other HTML tags. And these links were intended to be kept, so innerText was not enough.
The solution I decided to provide for everyone with the same issues. Surely, you can use it not only for tables, but for any elements. Here is the code:
/* Iterate over table data cells to insert a highlight tag */
function highlightSearchResults(textFilter) {
textFilter = textFilter.toLowerCase().replace('<', '<').replace('>', '>');
let tds;
tb = document.getElementById('sometable'); //root element where to search
if (tb) {
tds = tb.getElementsByTagName("td"); //sub-elements where to make replacements
}
if (textFilter && tds) {
for (td of tds) {
//specify your span class or whatever you need before and after
td.innerHTML = insertCaseInsensitive(td.innerHTML, textFilter, '<span class="highlight">', '</span>');
}
}
}
/* Insert a highlight tag */
function insertCaseInsensitive(srcStr, lowerCaseFilter, before, after) {
let lowStr = srcStr.toLowerCase();
let flen = lowerCaseFilter.length;
let i = -1;
while ((i = lowStr.indexOf(lowerCaseFilter, i + 1)) != -1) {
if (insideTag(i, srcStr)) continue;
srcStr = srcStr.slice(0, i) + before + srcStr.slice(i, i+flen) + after + srcStr.slice(i+flen);
lowStr = srcStr.toLowerCase();
i += before.length + after.length;
}
return srcStr;
}
/* Check if an ocurrence is inside any tag by index */
function insideTag(si, s) {
let ahead = false;
let back = false;
for (let i = si; i < s.length; i++) {
if (s[i] == "<") {
break;
}
if (s[i] == ">") {
ahead = true;
break;
}
}
for (let i = si; i >= 0; i--) {
if (s[i] == ">") {
break;
}
if (s[i] == "<") {
back = true;
break;
}
}
return (ahead && back);
}
Check this. I'm sure it will help you:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a global search and replace for "is" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = 'Is this "3" dris "3"?';
var allvar= '"3"';
var patt1 = new RegExp( allvar, 'g' );
document.getElementById("demo").innerHTML = str.replace(patt1,'"5"');
}
</script>
</body>
</html>
Here is the JSFiddle link.
I would suggest adding a global method for the string class by appending it to the prototype chain.
String.prototype.replaceAll = function(fromReplace, toReplace, {ignoreCasing} = {}) { return this.replace(new RegExp(fromReplace, ignoreCasing ? 'ig': 'g'), toReplace);}
And it can be used like:
'stringwithpattern'.replaceAll('pattern', 'new-pattern')