Emmanuel Akinfulubi

JavaScriptBasic

Find the longest word in a string in JavaScript

Beginner · 4 min read

Finding the longest word in a sentence is a classic beginner exercise and a common interview warm-up. It sounds like one line of code. It turns out to hide three small decisions: what counts as a space, what to do about punctuation, and which word wins when two are the same length.

In this tutorial you will write longestWord(sentence), which returns the longest word, and allLongest(sentence), which returns every word that shares the top length. You need to know what a string, an array and a function are. The string and array methods are explained as we go.

The plan

Every version of this exercise follows the same three moves:

  1. Cut the sentence into words.
  2. Clean each word so punctuation doesn't count towards its length.
  3. Walk through the words and keep the longest one seen so far.

Two tools: split and replace

split cuts a string into an array wherever it finds a separator:

JavaScript

console.log('red blue pink'.split(' ')); // [ 'red', 'blue', 'pink' ]

replace swaps part of a string for something else. With an empty string as the replacement, it deletes:

JavaScript

console.log('tutorial,'.replace(',', '')); // tutorial

Both methods also accept a regular expression, a small pattern written between slashes. Regular expressions let you say "any kind of space" or "anything that isn't a letter", which is exactly what this exercise needs.

Here is the exercise. Try it yourself first if you like, or follow the steps.

23 Longest word in a sentence

easy

Find the longest word in a sentence. Decide what to do about punctuation and about ties.

Stuck? Three hints, smallest first
  1. 1. Splitting on a single space breaks on double spaces and on newlines. Split on /\s+/ instead.
  2. 2. Strip punctuation before measuring, or "sentence." counts one character too many.
  3. 3. On a tie, reduce with > keeps the first; with >= it keeps the last. Pick deliberately.

Step 1: split on any whitespace

Splitting on a single space looks right until someone types two spaces:

JavaScript

console.log('Web  development'.split(' ')); // [ 'Web', '', 'development' ]

Between the two spaces there is nothing, so split puts an empty string there. A newline or a tab wouldn't be split at all. The pattern /\s+/ fixes both: \s means any whitespace character (space, tab, newline), and + means "one or more in a row".

JavaScript

console.log('Web  development\ntutorial'.split(/\s+/)); // [ 'Web', 'development', 'tutorial' ]

Step 2: strip the punctuation

'tutorial,' has 9 characters, but the word is only 8 long. We want to delete everything that isn't part of a word. The pattern for that is /[^\p{L}\p{N}'-]/gu. Piece by piece:

  • [...] matches one character from a set.
  • ^ at the start of the set flips it: "any character not in this set".
  • \p{L} is any letter in any language, so é and ñ count. \p{N} is any digit.
  • ' and - keep apostrophes and hyphens, so don't and well-being stay whole.
  • The g flag means "replace every match, not just the first". The u flag is needed for \p{...} to work.

JavaScript

const clean = (w) => w.replace(/[^\p{L}\p{N}'-]/gu, '');
console.log(clean('tutorial,'));   // tutorial
console.log(clean('well-being.')); // well-being
console.log(clean(','));           // an empty string

A word made only of punctuation becomes an empty string, so we filter those out. A sentence that starts with a space also produces an empty string at the front. Put together:

Step 2

function words(sentence) {
  return sentence
    .split(/\s+/)
    .map((w) => w.replace(/[^\p{L}\p{N}'-]/gu, ''))
    .filter((w) => w.length > 0);
}
console.log(words('Web  development  tutorial, and  well-being.'));
// [ 'Web', 'development', 'tutorial', 'and', 'well-being' ]

map changes every item, and filter keeps only the items that pass the test.

Step 3: keep the longest so far

Now walk through the words with reduce, which carries one value from item to item. Here that value is best, the longest word seen so far. It starts as an empty string, so any real word beats it.

Step 3

function longestWord(sentence) {
  return words(sentence).reduce((best, w) => (w.length > best.length ? w : best), '');
}
console.log(longestWord('Web  development  tutorial, and  well-being.')); // development
console.log(longestWord(''));                                            // an empty string

The ? : is the conditional operator: "if the new word is longer, keep it, otherwise keep best". An empty sentence has no words, so you get back the starting value, ''.

Step 4: decide what happens on a tie

In 'red blue pink', both blue and pink have four letters. With >, a later word has to be strictly longer to replace best, so the first one wins:

JavaScript

console.log(longestWord('red blue pink')); // blue

Change > to >= and an equal word also replaces best, so the last one wins and you get pink. Neither is wrong. What matters is choosing on purpose.

Often the most honest answer is to return every word that ties:

Step 4

function allLongest(sentence) {
  const list = words(sentence);
  const max = Math.max(0, ...list.map((w) => w.length));
  return list.filter((w) => w.length === max);
}
console.log(allLongest('red blue pink')); // [ 'blue', 'pink' ]
console.log(allLongest('cat dog bird'));  // [ 'bird' ]

... spreads the list of lengths into Math.max as separate numbers. The extra 0 matters for an empty sentence: Math.max() with nothing inside returns -Infinity, and the 0 keeps the result sensible.

The full solution

The complete answer has words, longestWord and allLongest, and runs them on a messy sentence with double spaces, a comma and a hyphen. Press Run to see the output.

The answer

function words(sentence) {
  return sentence
    .split(/\s+/)                      // any run of whitespace, not just one space
    .map((w) => w.replace(/[^\p{L}\p{N}'-]/gu, ''))   // drop punctuation, keep hyphens
    .filter((w) => w.length > 0);
}

// > keeps the FIRST of equal-length words. >= would keep the last.
function longestWord(sentence) {
  return words(sentence).reduce((best, w) => (w.length > best.length ? w : best), '');
}

function allLongest(sentence) {
  const list = words(sentence);
  const max = Math.max(0, ...list.map((w) => w.length));
  return list.filter((w) => w.length === max);
}

const s = 'Web  development  tutorial, and  well-being.';

console.log('words        :', words(s));
console.log('longest      :', longestWord(s));
console.log('all longest  :', allLongest('one three four'));

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('longest word found', longestWord(s), 'development');
test('punctuation stripped', words('tutorial,')[0], 'tutorial');
test('hyphenated words survive', words('well-being.')[0], 'well-being');
test('double spaces do not create empty words', words('a  b').length, 2);
test('a tie keeps the first', longestWord('one three four'), 'three');
test('or report every tie', allLongest('one three four'), ['three']);
test('a real tie', allLongest('cat dog bird'), ['bird']);
test('empty input', longestWord(''), '');

Three decisions hide in this small problem, and the question states none of them. Splitting on /\s+/ rather than ' ' survives double spaces and newlines. Stripping punctuation stops "tutorial," measuring 9. And on a tie, > versus >= silently changes which word you get — so allLongest is often the more honest answer.

Common mistakes

  • Splitting on ' '. Double spaces create empty words, and tabs or newlines aren't split at all. Use /\s+/.
  • Measuring words with their punctuation. 'tutorial,' is 9 characters, so a comma can make the wrong word win.
  • Not deciding about ties. > keeps the first, >= keeps the last. If both answers matter, return them all.

Try it yourself

  1. Write shortestWord(sentence). What starting value should reduce use this time?
  2. Return the length of the longest word instead of the word itself.
  3. Change allLongest so it never returns the same word twice, for example in 'blue blue pink'.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.