Home > Back-end >  How to swap first and last letter case in each word after using reverse() in JavaScript
How to swap first and last letter case in each word after using reverse() in JavaScript

Time:12-15

I wanna try swapping cases for the first and last letters in each word that are already reversed using the reverse function.

Let's say I have a string like this.

I am Firdaus

And I wanna make it just like this.

I ma Suadrif

Here is how the script looks like

let reverseWords = str => {
    console.log(`Input: ${str}`)
    let words = str.split(" ").map(word => {
        let chars = word.split("").reverse();
        let result = chars.map((char, index) => {
            if (index == chars.length-1 && chars.length != 0 && char == char.toUpperCase() && index != 0) {
                return char.toLowerCase();
            }
            return char;
        });
        return result.join('');
    });
    return words.join(' ');
}
console.log(`Output: ${reverseWords("I am Firdaus")}`);

If you run the code above, the result is not like what I expected

The uppercase F successfully becomes lowercase f, but the lowercase s failed to become uppercase S. I am confused about how to swap the s become an uppercase S.

Is there a way and the best way to make the string just like what I expected?

Thanks in advance.

CodePudding user response:

It look like you need to compare against the original string's casing to determine whether the returned character should be upper-cased or lower-cased. Use the index of the (reversed) character you're mapping over to access the original character at the same index in the original word.

const reverseWords = str => str
    .split(' ')
    .map(word => [...word].reverse()
        .map((char, i) => (
            word[i].toLowerCase() === word[i]
            ? char.toLowerCase()
            : char.toUpperCase()
        ))
        .join('')
    )
    .join(' ');
console.log(`Output: ${reverseWords("I am Firdaus")}`);

  • Related