1

I need to replace 1 with a 0, and replace 0 with 1 in a string. I know how to replace one thing with another, but how can I replace two separately. See the attempt below.

const broken = str => {
  return str.replace(/1/g, '0').replace(/0/g, '1');
}

This is an example:

input

011101

output

100010

2
  • 2
    I know I could do it in 2 stages Wouldn't work like that, then all 0s and 1s would be turned into 1s Commented Oct 20, 2018 at 20:29
  • @CertainPerformance you are dead right, I probably shouldn't have said that and only realised when I tried it :-D Commented Oct 20, 2018 at 20:29

1 Answer 1

1

You could take a function and an object for taking the replacement value.

const broken = str => str.replace(/[01]/g, match => ({ 0: 1, 1: 0 }[match]));

console.log(broken('1100'));

Sign up to request clarification or add additional context in comments.

4 Comments

what does the m mean?
it is the matched value.
This is exactly the same principle as in the duplicate question.
Another option which will work only in this particular situation would be to subtract from 1: match => 1 - match :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.