regex to replace two separate things separately in

2019-08-12 16:53发布

问题:

This question already has an answer here:

  • javascript swap characters in string 5 answers

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

回答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'));