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?
This question is related to
javascript
string
replace
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.replaceAll
behaves identically toString.prototype.replace
in all cases, except for the following two cases:
- If
searchValue
is a string,String.prototype.replace
only replaces a single occurrence of thesearchValue
, whereasString.prototype.replaceAll
replaces all occurrences of thesearchValue
(as if.split(searchValue).join(replaceValue)
or a global & properly-escaped regular expression had been used).- If
searchValue
is a non-global regular expression,String.prototype.replace
replaces a single match, whereasString.prototype.replaceAll
throws 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.replaceAll
behaves just likeString.prototype.replace
ifsearchValue
is a global regular expression.
You can see a spec-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(' ', '-')
);
_x000D_
str = "Test abc test test abc test test test abc test test abc"
str.split(' ').join().replace(/abc/g,'').replace(/,/g, ' ')
Here's a string prototype function based on the accepted answer:
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find, 'g'), replace);
};
EDIT
If your find
will contain special characters then you need to escape them:
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
Fiddle: http://jsfiddle.net/cdbzL/
For replacing a single time use:
var res = str.replace('abc', "");
For replacing multiple times use:
var res = str.replace(/abc/g, "");
For unique replaceable values
String.prototype.replaceAll = function(search_array, replacement_array) {_x000D_
//_x000D_
var target = this;_x000D_
//_x000D_
search_array.forEach(function(substr, index) {_x000D_
if (typeof replacement_array[index] != "undefined") {_x000D_
target = target.replace(new RegExp(substr, 'g'), replacement_array[index])_x000D_
}_x000D_
});_x000D_
//_x000D_
return target;_x000D_
};_x000D_
_x000D_
// Use:_x000D_
var replacedString = "This topic commented on :year. Talking :question.".replaceAll([':year', ':question'], ['2018', 'How to replace all occurrences of a string in JavaScript']);_x000D_
//_x000D_
console.log(replacedString);
_x000D_
As of August 2020, greenfield browsers have support for the String.replaceAll()
method defined by the ECMAScript 2021 language specification. For older/legacy browser support, the below still applies.
str = str.replace(/abc/g, '');
In response to comment:
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);
}
For replacing all kind of characters, try this code:
Suppose we have need to send " and \ in my string, then we will convert it " to \" and \ to \\
So this method will solve this issue.
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
var message = $('#message').val();
message = message.replaceAll('\\', '\\\\'); /*it will replace \ to \\ */
message = message.replaceAll('"', '\\"'); /*it will replace " to \\"*/
I was using Ajax, and I had the need to send parameters in JSON format. Then my method is looking like this:
function sendMessage(source, messageID, toProfileID, userProfileID) {
if (validateTextBox()) {
var message = $('#message').val();
message = message.replaceAll('\\', '\\\\');
message = message.replaceAll('"', '\\"');
$.ajax({
type: "POST",
async: "false",
contentType: "application/json; charset=utf-8",
url: "services/WebService1.asmx/SendMessage",
data: '{"source":"' + source + '","messageID":"' + messageID + '","toProfileID":"' + toProfileID + '","userProfileID":"' + userProfileID + '","message":"' + message + '"}',
dataType: "json",
success: function (data) {
loadMessageAfterSend(toProfileID, userProfileID);
$("#<%=PanelMessageDelete.ClientID%>").hide();
$("#message").val("");
$("#delMessageContainer").show();
$("#msgPanel").show();
},
error: function (result) {
alert("message sending failed");
}
});
}
else {
alert("Please type message in message box.");
$("#message").focus();
}
}
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
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;
};
I like this method (it looks a little cleaner):
text = text.replace(new RegExp("cat","g"), "dog");
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, the time is very short to be seen in the snippet)
console.time('split and join');_x000D_
"javascript-test-find-and-replace-all".split('-').join(' ');_x000D_
console.timeEnd('split and join')_x000D_
_x000D_
console.time('regular expression');_x000D_
"javascript-test-find-and-replace-all".replace(new RegExp('-', 'g'), ' ');_x000D_
console.timeEnd('regular expression');_x000D_
_x000D_
console.time('while');_x000D_
let str1 = "javascript-test-find-and-replace-all";_x000D_
while (str1.indexOf('-') !== -1) {_x000D_
str1 = str1.replace('-', ' ');_x000D_
}_x000D_
console.timeEnd('while');
_x000D_
The interesting thing to notice is that if you run them multiple time the results are always different even though the RegExp
solution seems the fastest on average and the while
loop solution the slowest.
My implementation, very self explanatory
function replaceAll(string, token, newtoken) {
if(token!=newtoken)
while(string.indexOf(token) > -1) {
string = string.replace(token, newtoken);
}
return string;
}
You can try like this:
Example data:
var text = "heloo,hai,hei"
text = text.replace(/[,]+/g, '')
or
text.forEach((value) => {
hasil = hasil.replace(',', '')
})
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)
str = str.replace(/abc/g, '');
Or try the replaceAll function from here:
What are useful JavaScript methods that extends built-in objects?
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.
E.g.
var output = "test this".replaceAll('this', 'that'); //output is 'test that'.
output = output.replaceAll('that', 'this'); //output is 'test this'
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(" ")
I use p to store the result from the previous recursion replacement:
function replaceAll(s, m, r, p) {
return s === p || r.contains(m) ? s : replaceAll(s.replace(m, r), m, r, s);
}
It will replace all occurrences in the string s until it is possible:
replaceAll('abbbbb', 'ab', 'a') ? 'abbbb' ? 'abbb' ? 'abb' ? 'ab' ? 'a'
To avoid infinite loop I check if the replacement r contains a match m:
replaceAll('abbbbb', 'a', 'ab') ? 'abbbbb'
//loop it until number occurrences comes to 0. OR simply copy/paste
function replaceAll(find, replace, str)
{
while( str.indexOf(find) > -1)
{
str = str.replace(find, replace);
}
return str;
}
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.
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
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).
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";_x000D_
_x000D_
var expectedString = str.replace(/abc(\s|$)/g, "");_x000D_
_x000D_
console.log(expectedString);
_x000D_
Use a regular expression:
str.replace(/abc/g, '');
Although people have mentioned the use of regex but there's a better approach if you want to replace the text irrespective of the case of the text. Like uppercase or lowercase. Use below syntax
//Consider below example
originalString.replace(/stringToBeReplaced/gi, '');
//Output will be all the occurrences removed irrespective of casing.
You can refer the detailed example here.
If what you want to find is already in a string, and you don't have a regex escaper handy, you can use join/split:
function replaceMulti(haystack, needle, replacement)_x000D_
{_x000D_
return haystack.split(needle).join(replacement);_x000D_
}_x000D_
_x000D_
someString = 'the cat looks like a cat';_x000D_
console.log(replaceMulti(someString, 'cat', 'dog'));
_x000D_
I would suggest adding a global method for string class by appending it to 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')
All the answers are accepted, 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";_x000D_
_x000D_
const compare = "abc";_x000D_
arrayStr = str.split(" ");_x000D_
arrayStr.forEach((element, index) => {_x000D_
if (element == compare) {_x000D_
arrayStr.splice(index, 1);_x000D_
}_x000D_
});_x000D_
const newString = arrayStr.join(" ");_x000D_
console.log(newString);
_x000D_
If you are trying to ensure that the string you are looking for won't exist even after the replacement, you need to use a loop.
For example:
var str = 'test aabcbc';
str = str.replace(/abc/g, '');
When complete, you will still have 'test abc'!
The simplest loop to solve this would be:
var str = 'test aabcbc';
while (str != str.replace(/abc/g, '')){
str.replace(/abc/g, '');
}
But that runs the replacement twice for each cycle. Perhaps (at risk of being voted down) that can be combined for a slightly more efficient but less readable form:
var str = 'test aabcbc';
while (str != (str = str.replace(/abc/g, ''))){}
// alert(str); alerts 'test '!
This can be particularly useful when looking for duplicate strings.
For example, if we have 'a,,,b' and we wish to remove all duplicate commas.
[In that case, one could do .replace(/,+/g,','), but at some point the regex gets complex and slow enough to loop instead.]
This is the fastest version that doesn't use regular expressions.
replaceAll = function(string, omit, place, prevstring) {
if (prevstring && string === prevstring)
return string;
prevstring = string.replace(omit, place);
return replaceAll(prevstring, omit, place, string)
}
It is almost twice as fast as the split and join method.
As pointed out in a comment here, this will not work if your omit
variable contains place
, as in: replaceAll("string", "s", "ss")
, because it will always be able to replace another occurrence of the word.
There is another jsperf with variants on my recursive replace that go even faster (http://jsperf.com/replace-all-vs-split-join/12)!
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"));
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);
_x000D_
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
There is a way to use the new "replaceAll" function.
But you need to use a cutting-edge browser or a javascript run time environment.
you can check the browser compatibility in here.
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
binary I am using.
RegExp.escape
is a separate issue to deal with, but 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 RegExp
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 SO dot com. 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)});
Here's very simple solution. You can assign a new method to 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
Check this answer may it will help and I used 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 "
Just add /g
document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');
to
// Replace 'hello' string with /hello/g regular expression.
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');
/g
means global
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 back-slash,
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?]
Most people are likely doing this to encode a URL. To encode a URL, you shouldn't only consider spaces, but convert the entire string properly with encodeURI
.
encodeURI("http://www.google.com/a file with spaces.html")
to get:
http://www.google.com/a%20file%20with%20spaces.html
The following function works for me:
String.prototype.replaceAllOccurence = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} ;
Now call the functions like this:
"you could be a Project Manager someday, if you work like this.".replaceAllOccurence ("you", "I");
Simply copy and paste this code in your browser console to TEST.
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 simplest way to this without using any regex 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(''));
_x000D_
Try this:
String.prototype.replaceAll = function (sfind, sreplace) {
var str = this;
while (str.indexOf(sfind) > -1) {
str = str.replace(sfind, sreplace);
}
return str;
};
while (str.indexOf('abc') !== -1)
{
str = str.replace('abc', '');
}
I added the function below to this perf 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 js implementation dependant.
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.
str = str.replace(new RegExp("abc", 'g'), "");
worked better for me than the above answers. so new RegExp("abc", 'g')
creates a RegExp what matches all occurence ('g'
flag) of the text ("abc"
). The second part is what gets replaced to, in your case empty string (""
).
str
is the string, and we have to override it, as replace(...)
just returns result, but not overrides. In some cases you might want to use that.
In November 2019 a new feature is added to the JavaScript string.prototype.replaceAll()
.
Currently it's only supported with babel.JS, but maybe in the future it can be implemented in all the browsers. For more information, read here.
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);
_x000D_
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
_x000D_
<p style="color:red">This snippet only presents codes used in tests. It not perform test itself!<p>
_x000D_
You can simply use below method
/**
* Replace all the occerencess of $find by $replace in $originalString
* @param {originalString} input - Raw string.
* @param {find} input - Target key word or regex that need to be replaced.
* @param {replace} input - Replacement key word
* @return {String} Output string
*/
function replaceAll(originalString, find, replace) {
return originalString.replace(new RegExp(find, 'g'), replace);
};
I know this isnt 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", "")
}
Using RegExp
in JavaScript could do the job for you, just simply do something like below code, don't forget the /g
after which standout for global:
var str ="Test abc test test abc test test test abc test test abc";
str = str.replace(/abc/g, '');
If you think of reuse, create a function to do that for you, but it's not recommended as it's only one line function, but again if you heavily use this, you can write something like this:
String.prototype.replaceAll = String.prototype.replaceAll || function(string, replaced) {
return this.replace(new RegExp(string, 'g'), replaced);
};
and simply use it in your code over and over like below:
var str ="Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');
But as I mention earlier, it won't make a huge difference in terms of lines to be written or performance, only caching the function may effect some faster performance on long strings and also a good practice of DRY code if you want to reuse.
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";_x000D_
_x000D_
var res = str.replace(/[abc]+/g, "");_x000D_
_x000D_
console.log(res);
_x000D_
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);
};
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.
function replaceAll(str, find, 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) + replaceAll(st2, find, replace);
}
}
return str;
}
In string first element search and replace
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'_x000D_
var i = str.replace('"[','[').replace(']"',']');_x000D_
console.log(i,'//first element search and replace')
_x000D_
In string global search and replace
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'_x000D_
var j = str.replace(/\"\[/g,'[').replace(/\]\"/g,']');_x000D_
console.log(j,'//global search and replace')
_x000D_
function replaceAll(str, find, replace) {
var $r="";
while($r!=str){
$r = str;
str = str.replace(find, replace);
}
return str;
}
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)
_x000D_
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
If using a library is an option for you then you will get the benefits of the testing and community support that goes with a library function. For example, the string.js library has a replaceAll() function that does what you're looking for:
// Include a reference to the string.js library and call it (for example) S.
str = S(str).replaceAll('abc', '').s;
Match against a global regular expression:
anotherString = someString.replace(/cat/g, 'dog');
Say you want to replace all the 'abc' with 'x':
let some_str = 'abc def def lom abc abc def'.split('abc').join('x')
console.log(some_str) //x def def lom x x def
I was trying to think about something more simple than modifying the string prototype.
In my apps, I use a custom function that is the most powerful for this purpose, and even wrapping the split/join
solution in the simpler case, it is a little bit faster in Chrome 60
and Firefox 54
(JSBEN.CH
) than other solutions. My computer runs Windows 7 64 bits
.
The advantage is that this custom function can handle many substitutions at the same time using strings or characters, which can be a shortcut for some applications.
Like a split/join
above solution, the solution below has no problem with escape characters, differently than regular expression approach.
function replaceAll(s,find,repl,caseOff,byChar){
if (arguments.length<2) return false;
var destDel = ! repl; // if destDel delete all keys from target
var isString = !! byChar; // if byChar, replace set of characters
if (typeof find !==typeof repl && ! destDel) return false;
if (isString && (typeof find!=="string")) return false;
if (! isString && (typeof find==="string")) {
return s.split(find).join(destDel?"":repl);
}
if ((! isString) && ( ! Array.isArray(find) ||
( ! Array.isArray(repl) && ! destDel) )) return false;
// if destOne replace all strings/characters by just one element
var destOne = destDel ? false : (repl.length===1);
// Generally source and destination should have the same size
if (! destOne && ! destDel && find.length!==repl.length) return false
var prox,sUp,findUp,i,done;
if (caseOff) { // case insensitive
// Working with uppercase keys and target
sUp = s.toUpperCase();
if (isString)
findUp = find.toUpperCase()
else
findUp = find.map(function(el){ return el.toUpperCase();});
} else { // case sensitive
sUp = s;
findUp =find.slice(); // clone array/string
}
done = new Array(find.length); // size: number of keys
done.fill(null);
var pos = 0; // initial position in target s
var r = ""; // initial result
var aux, winner;
while (pos < s.length) { // Scanning the target
prox = Number.MAX_SAFE_INTEGER;
winner = -1; // no winner at start
for (i=0;i<findUp.length;i++) // find next occurence for each string
if (done[i]!==-1) { // key still alive
// Never search for the word/char or is over?
if (done[i]===null || done[i]<pos) {
aux = sUp.indexOf(findUp[i],pos);
done[i]=aux; // Save the next occurrence
} else
aux = done[i] // restore the position of last search
if (aux<prox && aux!==-1) { // if next occurrence is minimum
winner = i; // save it
prox = aux;
}
} // not done
if (winner===-1) { // No matches forward
r += s.slice(pos);
break;
} // no winner
// found the character or string key in the target
i = winner; // restore the winner
r += s.slice(pos,prox); // update piece before the match
// Append the replacement in target
if (! destDel) r += repl[ destOne?0:i ];
pos = prox + ( isString?1:findUp[i].length ); // go after match
} // loop
return r; // return the resulting string
}
The documentation is below
replaceAll Syntax ====== replaceAll(s,find,[ repl ,caseOff, byChar) Parameters ========== "s" is a string target of replacement. "find" can be a string or array of strings. "repl" should be the same type than "find" or empty if "find" is a string, it is a simple replacement for all "find" occurrences in "s" by string "repl" if "find" is an array, it will replaced each string in "find" that occurs in "s" for corresponding string in "repl" array. The replace specs are independent: A replacement part cannot be replaced again. if "repl" is empty all "find" occurrences in "s" will be deleted. if "repl" has only one character or element, all occurrences in "s" will be replaced for that one. "caseOff" is true if replacement is case insensitive (default is FALSE) "byChar" is true when replacement is based on set of characters. Default is false if "byChar", it will be replaced in "s" all characters in "find" set of characters for corresponding character in "repl" set of characters Return ====== the function returns the new string after the replacement.
To be fair, I ran the benchmark with no parameter test.
Here is my test set, using Node.js
function l() { return console.log.apply(null, arguments); }
var k=0;
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
["ri","nea"],["do","fa"])); //1
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
["ri","nea"],["do"])); //2
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
["ri","nea"])); //3
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
"aeiou","","",true)); //4
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
"aeiou","a","",true)); //5
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
"aeiou","uoiea","",true)); //6
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
"aeiou","uoi","",true)); //7
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
["ri","nea"],["do","fa","leg"])); //8
l(++k,replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
["ri","nea"],["do","fa"])); //9
l(++k,replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
["ri","nea"],["do","fa"],true)); //10
return;
And the results:
1 'banana is a dope fruit harvested far the dover'
2 'banana is a dope fruit harvested dor the dover'
3 'banana is a pe fruit harvested r the ver'
4 'bnn s rp frt hrvstd nr th rvr'
5 'banana as a rapa fraat harvastad naar tha ravar'
6 'bununu is u ripo frait hurvostod nour tho rivor'
7 false
8 false
9 'BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER'
10 'BANANA IS A doPE FRUIT HARVESTED faR THE doVER'
var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);
Here is the working code with prototype:
String.prototype.replaceAll = function(find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g'), replace);
};
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 n
th 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**.**
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
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"
If the string contain similar pattern like abccc
, you can use this:
str.replace(/abc(\s|$)/g, "")
Replacing single quotes:
function JavaScriptEncode(text){
text = text.replace(/'/g,''')
// More encode here if required
return text;
}
Use Split and Join
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);
_x000D_
Update:
It's somewhat late for an update, but since I just stumbled on this question, and noticed that my previous answer is not one I'm happy with. Since the question involved replaceing a single word, it's incredible nobody thought of using word boundaries (\b
)
'a cat is not a caterpillar'.replace(/\bcat\b/gi,'dog');
//"a dog is not a caterpillar"
This is a simple regex that avoids replacing parts of words in most cases. However, a dash -
is still considered a word boundary. So conditionals can be used in this case to avoid replacing strings like cool-cat
:
'a cat is not a cool-cat'.replace(/\bcat\b/gi,'dog');//wrong
//"a dog is not a cool-dog" -- nips
'a cat is not a cool-cat'.replace(/(?:\b([^-]))cat(?:\b([^-]))/gi,'$1dog$2');
//"a dog is not a cool-cat"
basically, this question is the same as the question here: Javascript replace " ' " with " '' "
@Mike, check the answer I gave there... regexp isn't the only way to replace multiple occurrences of a subsrting, far from it. Think flexible, think split!
var newText = "the cat looks like a cat".split('cat').join('dog');
Alternatively, to prevent replacing word parts -which the approved answer will do, too! You can get around this issue using regular expressions that are, I admit, somewhat more complex and as an upshot of that, a tad slower, too:
var regText = "the cat looks like a cat".replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
The output is the same as the accepted answer, however, using the /cat/g expression on this string:
var oops = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/cat/g,'dog');
//returns "the dog looks like a dog, not a dogerpillar or cooldog" ??
Oops indeed, this probably isn't what you want. What is, then? IMHO, a regex that only replaces 'cat' conditionally. (ie not part of a word), like so:
var caterpillar = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
//return "the dog looks like a dog, not a caterpillar or coolcat"
My guess is, this meets your needs. It's not fullproof, of course, but it should be enough to get you started. I'd recommend reading some more on these pages. This'll prove useful in perfecting this expression to meet your specific needs.
http://www.javascriptkit.com/jsref/regexp.shtml
http://www.regular-expressions.info
Final addition:
Given that this question still gets a lot of views, I thought I might add an example of .replace
used with a callback function. In this case, it dramatically simplifies the expression and provides even more flexibility, like replacing with correct capitalisation or replacing both cat
and cats
in one go:
'Two cats are not 1 Cat! They\'re just cool-cats, you caterpillar'
.replace(/(^|.\b)(cat)(s?\b.|$)/gi,function(all,char1,cat,char2)
{
//check 1st, capitalize if required
var replacement = (cat.charAt(0) === 'C' ? 'D' : 'd') + 'og';
if (char1 === ' ' && char2 === 's')
{//replace plurals, too
cat = replacement + 's';
}
else
{//do not replace if dashes are matched
cat = char1 === '-' || char2 === '-' ? cat : replacement;
}
return char1 + cat + char2;//return replacement string
});
//returns:
//Two dogs are not 1 Dog! They're just cool-cats, you caterpillar
The simplest solution -
let str = "Test abc test test abc test test test abc test test abc";_x000D_
_x000D_
str = str.split(" ");_x000D_
str = str.filter((ele, key)=> ele!=="abc")_x000D_
str = str.join(" ")
_x000D_
Or simply -
str = str.split(" ").filter((ele, key) => ele != "abc").join(" ")
_x000D_
I use split and join or this funcion
function replaceAll( text, busca, reemplaza ){
while (text.toString().indexOf(busca) != -1)
text = text.toString().replace(busca,reemplaza);
return text;
}
Source: Stackoverflow.com