I am working on an assignment using javascript but I am stuck on a problem. When I try to join together several .replace commands i do not get the expected output. I do not use any libraries like Jquery.
var str = ('abc abc');
str = str.replace(/a/g, 'b').replace(/b/g, 'c');
alert(str);
With my code I get this output: ccc ccc. When I should get this: bcc bcc.
Can anyone see what I am doing wrong?
Best regards, a student from Norway :)
-
What you should get is exactly what you get. ;-) What you want to get might be different though. :-oRobG– RobG2014年10月01日 00:45:16 +00:00Commented Oct 1, 2014 at 0:45
1 Answer 1
Like @elclarns said, switch the replace functions so you are replacing b with c first.
str = str.replace(/b/g, 'c').replace(/a/g, 'b');
answered Oct 1, 2014 at 0:35
Donal
33.2k10 gold badges69 silver badges75 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
user2926446
Thanks for the example! Can you explain why it is like that?
cbayram
@user2926446, because code above executes left to right. second replace gets called on the result of the first replace.
lang-js