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

peter flanagan
  • 7,650
  • 21
  • 64
  • 112

1 Answers1

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'));
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358