Finding the Longest Word in a String with a regex

I was attempting to find the longest possible word inside a string. I thought an interesting solution would be to use a regex to find the longest possible string of characters inside spaces. My code looks like this:

function findLongestWordLength(str) {
  const regex = /([a-z]+)/gi;
  return str.match(regex).length;

This would return an array with all the words and not the longest. My code solution looks like this:

function findLongestWordLength(str) {
  const regex = /([a-z]+)/gi;
  const matches = str.match(regex);
  let last_longest = 0;
  for (let i = 0; i<matches.length; i++){
    if (matches[i].length > last_longest){
      last_longest = matches[i].length;
  return last_longest;

Is there any way to find the longest word in a string with an array?
The problem link is here: Problem

What if your string contains some ridiculous words like “you/be”.
I get it, in this problem there are no such test cases. But I myself would try to handle this for the sake of learning.
No thoughts about array for now.

But some time ago I was dealing with the same kind of stuff using Python.
I was using lists.
Python Lists and JS Arrays are somewhat similar. I think there is the way.

EDIT. No promises, but I can try to find relevant snippets on my PC. Such snippets written in Python, but I think i can ‘translate it’.

Why using Regex ?
I suggest to convert the string to an Array using split() method, and then find the longest word with a For Loop of array[i].length ( In each iteration you compare the current word length with the next one).

Hope that helps.

Yeah, I was exporting bunch of words separated by spaces from the file.
Stuff from file originally is a string.
Then I used type conversion, and every word became list element(in JS it will be array’s element).
Then I was looping through to find what I need.

It was not only the longest word, but some other stuff:
word with specific letters, word with capital letters etc

I understand and have looked at the solutions using an array. I just thought using a regex could theoretically would be faster than dividing the words into an array and searching it. Thank you for helping me.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.