Search code examples
javascriptstringvariablesswap

How to swap two adjacent characters in a string variable in Javascript


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.


Solution

  • 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.