-1

let string = 'abcdefghij'; the result I want string = 'abdcefhgij'. The changes should be made are cd to dc and gh to hg rest of the string is unaltered.

PVD
  • 27
  • 8

2 Answers2

0
    const string1 = 'abcdefghij'.replace(/[cd]/g, (c) => (c == 'c' ? 'd' : 'c'));
    console.log(string1);
    const string2 = string1.replace(/[gh]/g, (c) => (c == 'g' ? 'h' : 'g'));
    console.log(string2);

I did this. finally got the result in the form of string2. Anyone could suggest how to do it in one go?

PVD
  • 27
  • 8
0

To do it in one go, create a function that will map each characters you want to swap, like this:

function charReplace(char) {
    if(char == 'c') return 'd';
    if(char == 'd') return 'c';
    if(char == 'g') return 'h';
    if(char == 'h') return 'g';
}

Then you can pass this function as the second parameter to the replace function like this:

const originalString = 'abcdefghij';
const replacedString = originalString.replace(/[cdgh]/g, ($1) => charReplace($1));

If you need to map more chars, just add if blocks in the charReplace function. If it gets too long, you can implement it by keeping the map into an array and returning the element at the correct index.

Ivica Pesovski
  • 827
  • 7
  • 29