Ilya Kharlamov
Ilya Kharlamov

Reputation: 125

Replacing some characters in string JavaScript

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?

Upvotes: 1

Views: 1688

Answers (4)

Arun
Arun

Reputation: 582

This should work .. str.replace("A",D1)

Upvotes: 0

thiagoh
thiagoh

Reputation: 7418

this 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");

Upvotes: -1

Ruan Mendes
Ruan Mendes

Reputation: 92334

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];
})

Upvotes: 5

Esailija
Esailija

Reputation: 140234

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"

Upvotes: 2

Related Questions