0

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 :)

1
  • What you should get is exactly what you get. ;-) What you want to get might be different though. :-o Commented Oct 1, 2014 at 0:45

1 Answer 1

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

2 Comments

Thanks for the example! Can you explain why it is like that?
@user2926446, because code above executes left to right. second replace gets called on the result of the first replace.

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.