finn102
finn102

Reputation: 55

Stop .replace from replacing a character multiple times in Javascript

I have a string which will look something like "R U R' U' R' F R2 U' R' U' R U R' F'"

I want to replace all of the R's with F's, and all of the F's with R's. The issue is that when I use multiple .replaces like shown below, the R's are changed to F's and then changed back to R's, resulting in no change.

alg = alg.replace(/R/g, "F").replace(/F/g, "R");

Also, at the moment my .replaces are looking something like this:

alg = alg.replace(/R/g, "F");
alg = alg.replace(/L/g, "B")
alg = alg.replace(/F/g, "R");
alg = alg.replace(/B/g, "L");

Would there be a cleaner way to lay these out without stacking them all onto a single line?

I would greatly appreciate any help for both of these issues. Thanks.

Upvotes: 2

Views: 77

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371049

Use a single replace, with a replacer function, so that all the replacements happen at once, to ensure that a character that was just replaced won't be replaced again:

const input = "R U R' U' R' F R2 U' R' U' R U R' F";
const replaceObj = {
  R: 'F',
  F: 'R'
}
const output = input.replace(/[RF]/g, char => replaceObj[char]);
console.log(output);

Upvotes: 6

Related Questions