How to get the last word of a string in TypeScript

2 Answers

0 votes
const s = "typescript php c c++ c# python"; 
 
console.log(s.slice(s.lastIndexOf(' ') + 1));
 
   

/*
run:
   
python
   
*/

 



answered Jul 7, 2022 by avibootz
edited Mar 27 by avibootz
0 votes
/**
 * Returns the last word from a string.
 * Empty or whitespace-only strings return an empty string.
 */
function getLastWord(input: string): string {
    const trimmed = input.trim();

    if (trimmed === "") {
        return "";
    }

    // Split on whitespace and return the last element
    return trimmed.split(/\s+/).pop()!;
}

const tests: string[] = [
    "c# java php c c++ python typescript",
    "",
    "c#",
    "c c++ java ",
    "  "
];

tests.forEach((t, i) => {
    console.log(`${i + 1}. ${getLastWord(t)}`);
});



/*
run:

1. typescript
2. 
3. c#
4. java
5. 

*/

 



answered Mar 27 by avibootz
...