JavaScript: invertire le vocali di una stringa

In questo articolo vedremo invertire le vocali di una stringa con JavaScript.

JavaScript di Gabriele Romanato

In questo articolo vedremo invertire le vocali di una stringa con JavaScript.

JavaScript gestisce le stringhe come array di caratteri. Ciascun carattere, a sua volta, corrisponde ad un numero intero nell'insieme Unicode.

Possiamo sfruttare questa correlazione tramite la manipolazione degli array creando un array intermedio che contenga il carattere originario e il suo codice numerico che alla fine riconvertiremo in stringa.


'use strict';

const reverseVowels = (str = '') => {
    if(str.length === 0) {
        return str;
    }
    const vowels = 'aeiou'.split('');
    let count = 0;
    for(const ch of str) {
        
        if(vowels.includes(ch)) {
            count++;
        }
    }
    if(count < 2) {
        return str;
    }
    const chars = [];
    for(const ch of str) {
        chars.push([ch, ch.charCodeAt(0)]);
    }
    const outVowels = [];
    for(const c of chars) {
        let [a, b] = c;
        if(vowels.includes(a)) {
            outVowels.push(c);
        }
    }
    const length = outVowels.length;
    let i = -1;
    const revOutVowels = [];
    while(i < length) {
        i++;
        let curCh = outVowels[i];
        let nextI = i + 1;
        let nextCh =  nextI < length ? outVowels[nextI] : null;
        if(nextCh) {
            let a = [curCh[0], nextCh[1]];
            let b = [nextCh[0], curCh[1]];
            revOutVowels.push(a);
            revOutVowels.push(b);
        }
        
    }
    const output = [];

    for(const char of chars) {
        let [letter, code] = char;
        let uniCh = code;
        for(const chr of revOutVowels) {
            let [lett, cod] = chr;
            if(lett === letter) {
                uniCh = cod;
            }
        }
        output.push(uniCh);
    }
    return output.map(c => String.fromCharCode(c)).join('');
};

console.log(reverseVowels('hello'));