I need to replace multiple characters in a string. I have a line - "123AB"
And I need to replace the A at %D1, and B at %D2.
How do I do this? Can it be done with .replace, if so, how?
String.replace is very simple
"ABCDEFA".replace(/A/g, "a") // outputs "aBCDEFa"
"ABCDEFB".replace(/B/g, "b") // outputs "AbCDEFb"
So you could use
"123AB".replace(/A/g, "%D1").replace(/B/g, "%D2");
However, you can do it in one pass by passing a replacement function instead of a string to replace
"123AB".replace(/A|B/g, function(match) {
var repacements = {A: '%D1', B: '%D2'};
return replacements[match];
})
It's pretty straightforward, first argument is what you want to replace and second argument is what you want to replace it with:
var str = "123AB";
str = str.replace( "A", "%D1" ).replace( "B", "%D2");
//str is now "123%D1%D2"
"123ABABAB".replace( "A", "%D1" ).replace( "B", "%D2"); outputs "123%D1%D2ABAB" You need the regular expression to make it a global replacethis replaces all the occurencies
var rep = function (s, search, replacement) {
while(s.indexOf(search) >= 0)
s = s.replace(search, replacement);
return s;
}
var s = rep("123AB", "A", "%D1");
replace can do for yous.replace( /A/g, "%D1")O(n²) where as regex will be O(n)? even if you didn't realize that, regex is 50 times faster here jsperf.com/replace-vs-on2
String.replace. Read the API docs. developer.mozilla.org/en-US/docs/JavaScript/Reference/…