User Tools

Site Tools


java-script:reduce:find-longest-word-from-a-string

Find longest word from a string

The string is trimmed to remove any leading or trailing whitespace and split into an array of words using the regex /\s+/, which matches one or more whitespace characters:
The function uses the reduce method on the array of words to find the longest word. The reduce method takes a callback function that compares the length of the current word to the length of the longest word found so far (maxWord):
.reduce((maxWord, word) => {
    return word.length > maxWord.length ? word : maxWord;
}, '')
longest-word-string.js
function findLongestWord(string) {
    if (typeof string !== 'string' || string.trim().length === 0) {
        return '';
    }
 
    return string.trim().split(/\s+/).reduce((maxWord, word) => {
        return word.length > maxWord.length ? word : maxWord;
    }, '');
}
 
let longestWord = findLongestWord(" abc def ghiiii axiiii ");
console.log(longestWord); // Output: "ghiiii"
java-script/reduce/find-longest-word-from-a-string.txt · Last modified: 2023/08/07 21:04 by odefta