WOHOOO... A NEW WAY!

Continuing the discussion from freeCodeCamp Challenge Guide: Find the Longest Word in a String:

Hello, friends and everyone present in the community to whom I owe so much for letting all of us share and learn for free. Anyways I’ll not waste your time and come to the point that there is another way of doing this particular problem { Find the Longest Word in a String} using regex. Yes, you heard me right REGEX. Those complex statements of .match() and .test(). I’m posting this solution in the community so anyone interested can ask questing and since we have been through the REGEX module, it will be easy to understand for you. Thank you and if you like the solution then feel free drop a heart. Happy coding to all.

function findLongestWordLength(str) {
let x = /.[a-z]*.*?\s|.[a-z]*.*?/gi;
let y = str.match(x);
//return y;
let z= ;
for (let i = 0; i< y.length-1 ;i++){
if (y[i].length > z.length){
z = y[i];
}
}
if (y[y.length - 1].length > z.length){
z = y[y.length - 1];
return z.length;
}
else{
return z.length - 1;
}
}
console.log(findLongestWordLength(“What if we try a super-long word such as otorhinolaryngology”));

You can post solutions that invite discussion (like asking how the solution works, or asking about certain parts of the solution). But please don’t just post your solution for the sake of sharing it.
If you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

1 Like

okay, I’ll keep that in mind from next time.

Yes, you can definitely use a regex to split the string into an array of words instead of using split. Your regex is including the space after each word though, which is why you need to include the - 1 on the end of your second return statement.

Now I will give you a challenge. There is a much simpler regex pattern you can use that will accomplish the same thing and not include the space after the word so that you can get rid of that - 1.

Also, I would highly recommend you use better variable names than x, y, and z. I don’t think this solution would be accepted by FCC to add to the hints page.

And another challenge. You can get rid of the if/else completely at the end and just use one return statement, but you’ll need to make a few adjustments to your for loop.

Great advice, I’ll keep in mind, to use variables which are easy to understand (rather than using x, y, and z). I never posted this with an intent of getting this solution published on FCC.
I already solved this challenge conventionally, and wanted to solve it again differently so I just took a challenge and shared my results.

Indeed there is a lot of room for improvement. :smiley:

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