Replace all without regex where I can use G

So, I have the following:

var token = '[token]'; var tokenValue = 'elephant'; var string = 'i have a beautiful [token] and i sold my [token]'; string = string.replace(token, tokenValue); 

The above will replace only the first [token] and leave the second on.

If I used a regex, I could use it as

 string = string.replace(/[token]/g, tokenValue); 

And that will replace all my [tokens]

However, I do not know how to do this without using //

+10
source share
7 answers

Why not replace the token every time it appears with a do while loop?

 var index = 0; do { string = string.replace(token, tokenValue); } while((index = string.indexOf(token, index + 1)) > -1); 
+9
source

I found split / join satisfactory enough for most of my cases. Real life example:

 myText.split("\n").join('<br>'); 
+15
source
 string = string.replace(new RegExp("\\[token\\]","g"), tokenValue); 
+3
source
 "[.token.*] nonsense and [.token.*] more nonsense".replace("[.token.*]", "some", "g"); 

Will produce:

"some stupidity and some other stupidity"

+1
source

I realized that the answer from @TheBestGuest will not work for the following example, since you will end up in an infinite loop:

 var stringSample= 'CIC'; var index = 0; do { stringSample = stringSample.replace('C', 'CC'); } while((index = stringSample.indexOf('C', index + 1)) > -1); 

So here is my suggestion for the replaceAll method written in TypeScript:

 let matchString = 'CIC'; let searchValueString= 'C'; let replacementString ='CC'; matchString = matchString.split(searchValueString).join(replacementString); console.log(matchString); 
+1
source

you can get the first event using indexOf:

 var index=str.indexOf(token); 

and then replace it as a function

 String.prototype.replaceAt=function(index, tokenvalue) { return this.substr(0, index) + character + this.substr(index+character.length); } 
0
source

Caution with the accepted answer, the replaceWith line may contain the inToReplace line, in which case there will be an infinite loop ...

Here is the best version:

 function replaceSubstring(inSource, inToReplace, inReplaceWith) { var outString = []; var repLen = inToReplace.length; while (true) { var idx = inSource.indexOf(inToReplace); if (idx == -1) { outString.push(inSource); break; } outString.push(inSource.substring(0, idx)) outString.push(inReplaceWith); inSource = inSource.substring(idx + repLen); } return outString.join(""); } 
0
source

Source: https://habr.com/ru/post/1483258/


All Articles