User Tools

Site Tools


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

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java-script:reduce:find-longest-word-from-a-string [2023/08/07 20:56] – removed - external edit (Unknown date) 127.0.0.1java-script:reduce:find-longest-word-from-a-string [2023/08/07 21:04] (current) odefta
Line 1: Line 1:
 +====== Find longest word from a string ======
 +
 +<note>
 +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**:
 +</note>
 +
 +<note>
 +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):
 +<code javascript>
 +.reduce((maxWord, word) => {
 +    return word.length > maxWord.length ? word : maxWord;
 +}, '')
 +</code>
 +</note>
 +
 +<code javascript 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"
 +</code>