JavaScript: reperire la lunghezza dell'ultima parola in una stringa

In questo articolo vedremo come ottenere la lunghezza dell'ultima parola in una stringa con JavaScript.

JavaScript di Gabriele Romanato

In questo articolo vedremo come ottenere la lunghezza dell'ultima parola in una stringa con JavaScript.

Possiamo utilizzare la seguente funzione.


'use strict';

const lengthOfLastWord = s => {
    if(typeof s !== 'string' || s.length === 0) {
        return 0;
    }
    const LIMIT = 10000;
    if(s.length > LIMIT) {
        return 0;
    }
    const parts = s.trim().split(/\s/);
    if(parts.length === 0) {
        return 0;
    }
    if(parts.length === 1) {
        return parts[0].trim().length;
    }
    const values = parts.filter(v => !/^\s+$/.test(v));
    if(values.length === 0) {
        return 0;
    }
    if(values.length === 1) {
        return values[0].length;
    }
    const lastWord = values[values.length - 1];
    return lastWord.length;
};

Esempio d'uso:


const main = () => {
    const tests = ['Hello World', '   fly me   to   the moon  ',
             'luffy is still joyboy'];
    for(const test of tests) {
        console.log(test, lengthOfLastWord(test));
    }         
};

main();