1

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?

1

4 Answers 4

5

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];
})
Sign up to request clarification or add additional context in comments.

Comments

2

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"

4 Comments

yes it does, it replaces the a and the b as op requested :I
@Esailija It only works for the input the OP requested, not if there are multiple As or Bs. "123ABABAB".replace( "A", "%D1" ).replace( "B", "%D2"); outputs "123%D1%D2ABAB" You need the regular expression to make it a global replace
@JuanMendes yes I know that, but the op asked for a simple replace that works for his input :-p
@Esailija That is a sample string, you can't assume that is the only possible input, can you?
0

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

Comments

-1

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

6 Comments

Yes, it works, but you're duplicating work that replace can do for you
If global replace was necessary, you could have just done global replace ... s.replace( /A/g, "%D1")
@IlyaKharlamov This is the worst answer out of all the available ones
but you're using regular expressions.. they are slower than mine verification.. bad for you.. =\
You do realize that this is 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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.