Function to find the longest word in JavaScript
Beginner · 4 min read
Finding the longest word in a sentence is a small task with one hidden decision. 'Web Development Tutorial' should give 'Development', which is easy. But what about 'Lagos Abuja', where both words have five letters? Your code will pick one of them, and in this tutorial you will learn to pick on purpose.
You will write a function called longestWord using split and reduce. Then you will write versions that return the last of a tie, and all the tied words. You need to know what a function and an array are. reduce is explained from scratch.
What reduce does
reduce walks through an array and carries one value along as it goes. You give it a function and a starting value. For each item, the function receives the value carried so far and the current item, and returns the new carried value. At the end, reduce hands you the last one.
Here it adds up numbers. The carried value starts at 0:
const total = [3, 5, 2].reduce((sum, n) => sum + n, 0);
console.log(total); // 10
It goes 0 + 3 = 3, then 3 + 5 = 8, then 8 + 2 = 10. To find the longest word, the carried value will be "the longest word so far".
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
6 Find the longest word
easy'Web Development Tutorial' should give 'Development'. Decide what to do when two words tie.
Stuck? Three hints, smallest first
- 1. Split into words, then reduce keeping the longest so far.
- 2.
>versus>=in the comparison decides whether the first or last of a tie wins. - 3. Split on
/\s+/after trimming, so runs of spaces do not create empty words.
Step 1: split the sentence into words
split(' ') cuts at single spaces, but extra spaces leave empty strings behind. Splitting on the pattern /\s+/ instead treats any run of spaces as one break. \s means any whitespace character (a space, tab or new line), and + means "one or more":
console.log(' Web Development '.split(' ').length); // 8
console.log(' Web Development '.trim().split(/\s+/)); // [ 'Web', 'Development' ]
trim() removes spaces at both ends first, so there is no empty piece at the start or end. The answer also adds .filter(Boolean), which drops any empty string that is left. That matters for an input like '', where split would return [''].
Step 2: keep the longest so far
Now reduce, starting with an empty string. Each word is compared with the longest so far, and the longer one is carried forward:
function longestWord(text) {
const words = text.trim().split(/\s+/).filter(Boolean);
return words.reduce((longest, w) => (w.length > longest.length ? w : longest), '');
}
console.log(longestWord('Web Development Tutorial')); // 'Development'
console.log(longestWord('')); // ''
Follow it for the example: '' vs Web keeps Web; Web vs Development keeps Development; Development vs Tutorial keeps Development.
Starting with '' means an empty sentence returns '' instead of throwing an error. Without a starting value, reduce on an empty array throws a TypeError.
Step 3: the tie, decided by one character
Look closely at w.length > longest.length. When a word is the same length as the longest so far, > is false, so the old word stays. That means the first word of a tie wins. Change > to >= and a word of equal length replaces it, so the last one wins:
const lastLongest = (text) =>
text.trim().split(/\s+/).filter(Boolean).reduce((l, w) => (w.length >= l.length ? w : l), '');
console.log(longestWord('Lagos Abuja')); // 'Lagos'
console.log(lastLongest('Lagos Abuja')); // 'Abuja'
Same input, different answers, from one character. Whenever you write a "find the biggest" reduce, decide which one you mean.
Step 4: return every tied word
Often you want all the winners. First find the longest length, then keep every word that has it:
function allLongest(text) {
const words = text.trim().split(/\s+/).filter(Boolean);
const max = Math.max(0, ...words.map((w) => w.length));
return words.filter((w) => w.length === max);
}
console.log(allLongest('Lagos Abuja Kano')); // [ 'Lagos', 'Abuja' ]
console.log(Math.max()); // -Infinity
words.map((w) => w.length) makes an array of lengths, and ... spreads them into Math.max as separate numbers. The 0 at the front is a guard. With no words at all, Math.max() gets nothing and returns -Infinity, as the last line shows. With the 0, it returns 0 instead.
Step 5: punctuation counts
console.log(longestWord('hi there!')); // 'there!'
console.log(longestWord('hi there!'.replace(/[^\w\s]/g, ''))); // 'there'
The ! is part of the word, so it adds to its length. If you don't want that, strip punctuation first. [^\w\s] means "anything that is not a word character or whitespace".
The full solution
The panel has longestWord, lastLongest and allLongest. It prints the example, the 'Lagos Abuja' tie both ways, every tied word, the extra-spaces case and the empty string. Press Run to see them.
function longestWord(text) {
const words = text.trim().split(/\s+/).filter(Boolean);
// > , not >= : the FIRST of a tie wins. Make the choice on purpose.
return words.reduce((longest, w) => (w.length > longest.length ? w : longest), '');
}
// The other choice, for comparison.
const lastLongest = (text) =>
text.trim().split(/\s+/).filter(Boolean).reduce((l, w) => (w.length >= l.length ? w : l), '');
// Every word tied for longest, which is often what you actually wanted.
function allLongest(text) {
const words = text.trim().split(/\s+/).filter(Boolean);
const max = Math.max(0, ...words.map((w) => w.length));
return words.filter((w) => w.length === max);
}
console.log("longestWord('Web Development Tutorial') =", longestWord('Web Development Tutorial'));
console.log('a tie, first wins :', longestWord('Lagos Abuja'), ' last wins:', lastLongest('Lagos Abuja'));
console.log('all of them :', allLongest('Lagos Abuja Kano'));
console.log('extra spaces :', longestWord(' Web Development '));
console.log('empty string :', JSON.stringify(longestWord('')));
Output
13 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 13 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the example in the question", longestWord('Web Development Tutorial'), 'Development');
test('a single word is the longest', longestWord('Lagos'), 'Lagos');
test('an empty string gives an empty string', longestWord(''), '');
test('a string of spaces does too', longestWord(' '), '');
test('runs of spaces do not create empty words', longestWord(' Web Development '), 'Development');
test('a tie goes to the first, with >', longestWord('Lagos Abuja'), 'Lagos');
test('and to the last, with >=', lastLongest('Lagos Abuja'), 'Abuja');
test('which is the whole reason to choose deliberately', longestWord('Lagos Abuja') === lastLongest('Lagos Abuja'), false);
test('every tied word can be returned instead', allLongest('Lagos Abuja Kano'), ['Lagos', 'Abuja']);
test('and a clear winner comes back alone', allLongest('Web Development Tutorial'), ['Development']);
test('an empty string gives no longest words', allLongest(''), []);
test('punctuation counts as part of the word', longestWord('hi there!'), 'there!');
test('unless you strip it first', longestWord('hi there!'.replace(/[^\w\s]/g, '')), 'there');
> versus >= is the entire content of this exercise. With > the first of a tie wins, with >= the last does, and the assertion showing the two disagree on 'Lagos Abuja' is there so the choice cannot be accidental. The same one-character decision appears in every "find the best" reduce you will write.
Often neither is right and you want all the winners, which is why allLongest is here. Note Math.max(0, ...words.map(...)) — the 0 guards the empty case, since Math.max() with no arguments returns -Infinity.
Splitting on /s+/ after trim() handles runs of spaces. And punctuation counts as part of a word unless you remove it, which the last two assertions make explicit rather than leaving as a surprise.
Common mistakes
- Splitting on a single space. Extra spaces create empty words, and
filteror/\s+/is needed to remove them. - Calling
reducewith no starting value. On an empty array it throws a TypeError. Pass''. - Choosing
>or>=by accident. One picks the first of a tie and the other the last. Choose on purpose.
Try it yourself
- Write
shortestWord(text). Which comparison do you need, and what starting value works? (Hint:''won't.) - Return the length of the longest word instead of the word.
- Change
allLongestso it never returns the same word twice, for an input like'abuja lagos abuja'.