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?
After several trials and a lot of fails I found that the below function seemsto be the best all rounder when it comes to browser compatability, 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 apps still make heavy use of OLE browsers (such as old VB6 apps or excel xlsm macros with forms)
Anyway, here's the simple function.
function replaceAll(str, match, replacement){
return str.split(match).join(replacement);
}
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
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);
};
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.
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 "
With Regex i flag for case insensitive
console.log('App started'.replace(/a/g, '')) // App strted
console.log('App started'.replace(/a/gi, '')) // pp strted
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;
}
replaceAll("123434", "1234", "12")
should return "1234"
but instead returns "12"
.
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'
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);
};
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;
}
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?]
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(" ")
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 be <2020?
In this case we need polyfill (Forcing older browsers to support new features) (I think for a few years 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
IE 9+ (Tested on IE11)
All other browsers (after 2012)
The result is same as the native replaceAll in case of first argument input be:
null
, undefined
, Object
, Function
, Date
, ... , RegExp
, Number
, String
, ...
Ref: https://tc39.es/ecma262/#sec-string.prototype.replaceall + RegExp Syntax
Important note: As some professionals mention it, many of recursive functions that suggested in answers, will return wrong result. (Try them with the Challenged case of above snippet)
Maybe some tricky methods like .split('searchValue').join('replaceValue')
or Some well managed functions give same result, but definitely 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 advance 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/Node) is definitely for around 2012-2021, also is a Standard/Famous one, so do not require any special consideration.
But there can be even older browsers OR some unexpected problems, and polyfills still can support & solve more possible environment problems. So in case we need maximum support that possible, we can use polyfill libraries
like:
Specially for replaceAll:
<script src="https://polyfill.io/v3/polyfill.min.js?features=String.prototype.replaceAll"></script>
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
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'
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');
"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 time the results are always different even though the RegExp
solution seems the fastest on average and the while
loop solution the slowest.
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;
function replaceAll(str, find, replace) {
var $r="";
while($r!=str){
$r = str;
str = str.replace(find, replace);
}
return 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);
};
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(' ', '-')
);
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
In string first element search and replace
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'
var i = str.replace('"[','[').replace(']"',']');
console.log(i,'//first element search and replace')
In string global search and replace
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'
var j = str.replace(/\"\[/g,'[').replace(/\]\"/g,']');
console.log(j,'//global search and replace')
For unique replaceable values
String.prototype.replaceAll = function(search_array, replacement_array) {
//
var target = this;
//
search_array.forEach(function(substr, index) {
if (typeof replacement_array[index] != "undefined") {
target = target.replace(new RegExp(substr, 'g'), replacement_array[index])
}
});
//
return target;
};
// Use:
var replacedString = "This topic commented on :year. Talking :question.".replaceAll([':year', ':question'], ['2018', 'How to replace all occurrences of a string in JavaScript']);
//
console.log(replacedString);
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.JS, 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);
};
Try this:
String.prototype.replaceAll = function (sfind, sreplace) {
var str = this;
while (str.indexOf(sfind) > -1) {
str = str.replace(sfind, sreplace);
}
return str;
};
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)
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"));
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**.**
aba
inababa
withca
, which result do you expect?caba
?abca
?cca
?String.prototype.replaceAll()
is now a standard part of ECMAScript tc39.es/ecma262/#sec-string.prototype.replaceall, documented at developer.mozilla.org/docs/Web/JavaScript/Reference/… and shipped in Safari 13.1, Firefox 77 and Chrome Dev/Canary and will ship in Chrome 85. From the docs: “If searchValue is a string, replaces all occurrences of searchValue (as if.split(searchValue).join(replaceValue)
or a global & properly-escaped regular expression had been used). If searchValue is a non-global regular expression, throws an exception”str.replace(/abc/g, '');
so g to get all matches.