How to get the word before the last word from a string (edge‑case‑safe) in JavaScript

1 Answer

0 votes
/**
 * Returns the word before the last word.
 * Uses Unicode-aware regex to handle international scripts.
 */
function getWordBeforeLast(text) {
    // \p{L} matches any Unicode letter (works for English, Kanji, Cyrillic, etc.)
    // \p{N} matches any Unicode number
    // We split by anything that is NOT a letter or a number ([^\p{L}\p{N}]+)
    // The 'u' flag is required to enable Unicode property support.
    const words = text.split(/[^\p{L}\p{N}]+/u).filter(word => word.length > 0);

    if (words.length < 2) {
        return "null";
    }

    // Accessing the second to last element using negative indexing (ES2022+)
    return words.at(-2);
}

function main() {
    console.log("=== Testing: Get Word Before Last ===\n");

    const tests = [
        "python javascript",
        "  many   spaces   here   now  ",
        "OneWord",
        "",
        "   ",
        "Hello, world!",
        "Tabs\tand\nnewlines work too",
        "Unicode 世界、こんにちは",
        "Ends with punctuation.",
        "Multiple words, with punctuation, here!",
        "state-of-the-art program example"
    ];

    tests.forEach(t => {
        const result = getWordBeforeLast(t);
        
        console.log(`Input: "${t}"`);
        console.log(`Output: ${result}`);
        console.log("-".repeat(40));
    });
}

main();



/*
OUTPUT:

=== Testing: Get Word Before Last ===

Input: "python javascript"
Output: python
----------------------------------------
Input: "  many   spaces   here   now  "
Output: here
----------------------------------------
Input: "OneWord"
Output: null
----------------------------------------
Input: ""
Output: null
----------------------------------------
Input: "   "
Output: null
----------------------------------------
Input: "Hello, world!"
Output: Hello
----------------------------------------
Input: "Tabs	and
newlines work too"
Output: work
----------------------------------------
Input: "Unicode 世界、こんにちは"
Output: 世界
----------------------------------------
Input: "Ends with punctuation."
Output: with
----------------------------------------
Input: "Multiple words, with punctuation, here!"
Output: punctuation
----------------------------------------
Input: "state-of-the-art program example"
Output: program
----------------------------------------

*/

 



answered Mar 29 by avibootz
edited Mar 29 by avibootz

Related questions

...