Find the Longest Word in a String with regular expression [Spoiler]


function findLongestWord(str) {
  return(str.replace(/\w/g,"1").split(" ").sort().pop().length);

findLongestWord("The quick brown fox jumped over the lazy dog");

Hello my friend,

Do you have a question?

your algorithm seems to work?

It is not a question, it works.

Yes it does :thumbsup:

Its also much much shorter than mine - I hear that alot tho :grin:

function findLongestWord(str) {
  var strArr = str.split(" ");
  strArr.sort(function (a, b) {
  return b.length - a.length;
   return strArr[0].length;

findLongestWord("What is the average airspeed velocity of an unladen swallow");
1 Like

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

I also added a [Spoiler] tag to your post title. Please warn people if you are showing working solutions, rather than asking for help.

Nice use of chained methods :slight_smile:


I found shorter:

findLongestWord=(str)=>(str.replace(/\w/g,"1").split(" ").sort().pop().length);
findLongestWord("The quick brown fox jumped over the lazy dog");
1 Like

Ibarjak, I know it’s been a while since you posted your solution, but would you mind reading your code by typing it as a story? I’d like to get an explanation or insight as to how you are reading code to get in that mental wave. THANKS!

I’m going to give it a shot, so correct me if I’m wrong!

First, you replace every character in your string by adding a “1” to each character based on your regular expression (/\w) and does a global search based on your modifier (/g).

Then you split the string every time it encounters " " in the string.

You sort out the array by ascending order.

The (pop) method is used to remove that last element and return it to the console.

Then you get the length from that last element in the array after the sort.

My question is, when do you create the array in your code?

1 Like

Yes, that is. The string was not an issue, only the string’s length.
Make an array: “The quick brown fox jumped over the lazy dog”.split(" ");

1 Like

Great job @lbarjak.
Only thing I’d add so that it’s good long term the code since we are moving to the new beta soon and it’ll keep yours relevant forever since it’ll include the original code, the question and your solution.

PS. ES6 generally will always be shorter by the way, there is no getting around it, but your ES5 solution is top notch. Also I totally agree with @JacksonBates, this is a really great use of chaining methods. I try to do it quite often and I break stuff all the time, but I’ll get there, especially with great examples like yours.

Thx. @misterhtmlcss
It may be reduced :smiley:

findLongestWord=(str)=>str.replace(/\w/g,'.').split(' ').sort().pop().length
1 Like

Hi @lbarjak sorry I meant I saw your ES6 version and that for me there wasn’t much to say, because the genius was in your ES5 solution. Writing using ES6 is shorter, but that’s more a conversion than anything, still good, but the respect was already there from the ES5 original. Good job man and good for you for learning ES6!! Sorry I wasn’t clear, I only realized after you reposted your ES6 again that I’d missed some critical words to communicate my true meaning. Keep rocking the posts man. I love refactoring too.

PS. You should build in some error detection and management code too man. That’s fly in my books. :wink:

1 Like

I just did this one a few days ago so it got my attention. I enjoyed working on it. Here’s my solution, probably more lines than needed:

var strArray = str.split(" ");
var newLength = 0;
var eachWord; 

for (var i = 0; i < strArray.length; i ++) {
eachWord = strArray[i].length;
if (eachWord > newLength) {
newLength = eachWord;
  return newLength;

findLongestWord("The quick brown fox jumped over the lazy dog");

Interesting how there can be so many different approaches to a problem. Your solution is a lot more elegant than mine.

1 Like
function findLongestWord(str) {
  str = str.split(" ");
  var a = str[0].length; //longest?
  for (i = 1; i < str.length; i++) if (a < str[i].length) a = str[i].length;
  return a;

findLongestWord("The quick brown fox jumped over the lazy dog");

Without split (and array):

function findLongestWord(str){
  var res = 0, tmp = 0;
  for(i = 0; i < str.length; i++){
    if (str[i] == ' ') tmp = 0;
    if (res < tmp) res = tmp;
  return res;

findLongestWord("The quick brown fox jumped over the lazy dog");

Reduce hasn’t been used yet :slight_smile:

function findLongestWord(str) {
  return str.split(' ').reduce((a, c) => a = c.length > a ? c.length : a, 0);

findLongestWord("The quick brown fox jumped over the lazy dog");

Completely forgot about `Math.max’.

function findLongestWord(str) {
    return str.split(' ').reduce((a, c) => a = Math.max(a, c.length), 0);

findLongestWord("The quick brown fox jumped over the lazy dog");
1 Like

So it works:

findLongestWord=(str)=>str.split(' ').sort((a, b)=>a.length-b.length).pop().length

@jenovs Super!
Other solution with Math.max:

findLongestWord=(str)=>Math.max(...str.split(' ').map(x=>x.split('').length))

shortest …so far

findLongestWord=(str)=>Math.max(...str.split(' ').map(x=>x.length))

@misterhtmlcss step by step

// findLongestWord=(str)=>Math.max(...str.split(' ').map(x=>x.length))
// step by step
function findLongestWord(str){ // ES6 arrow function, findLongestWord=(str)=>
  str = str.split(' '); // string to array, [ 'The','quick','brown','fox','jumped','over','the','lazy','dog' ]
  str = => x.length); // words to length of words, [ 3, 5, 5, 3, 6, 4, 3, 4, 3 ]
  str = Math.max(...str); // = 6, (...str), spread the array to variables
  return str;