How to reverse only the alphabetic characters in a string, keeping other characters in place with JavaScript

1 Answer

0 votes
function reverseOnlyAlphabeticCharacters(s) {
    const chars = s.split("");
    let i = 0;
    let j = chars.length - 1;

    const isLetter = ch => /[A-Za-z]/.test(ch);

    while (i < j) {
        if (!isLetter(chars[i])) {
            i++;
        } else if (!isLetter(chars[j])) {
            j--;
        } else {
            const tmp = chars[i];
            chars[i] = chars[j];
            chars[j] = tmp;
            i++;
            j--;
        }
    }

    return chars.join("");
}

const s = "a1-bC2-dEf3-ghIj";

console.log(s);
console.log(reverseOnlyAlphabeticCharacters(s));



/*
run:

a1-bC2-dEf3-ghIj
j1-Ih2-gfE3-dCba

*/

 



answered Mar 6 by avibootz
edited Mar 6 by avibootz

Related questions

...