java-script:reduce:find-longest-word-from-a-string
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext 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.1 | java-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 ====== | ||
+ | |||
+ | < | ||
+ | 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): | ||
+ | <code javascript> | ||
+ | .reduce((maxWord, | ||
+ | return word.length > maxWord.length ? word : maxWord; | ||
+ | }, '' | ||
+ | </ | ||
+ | </ | ||
+ | |||
+ | <code javascript longest-word-string.js> | ||
+ | function findLongestWord(string) { | ||
+ | if (typeof string !== ' | ||
+ | return ''; | ||
+ | } | ||
+ | |||
+ | return string.trim().split(/ | ||
+ | return word.length > maxWord.length ? word : maxWord; | ||
+ | }, '' | ||
+ | } | ||
+ | |||
+ | let longestWord = findLongestWord(" | ||
+ | console.log(longestWord); | ||
+ | </ | ||