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

Hi Tony,

It’s true we all have different ways of writing to get the same result. It’s fun to do like writing and wordsmithing an Ad.

However one thing you should know is that variables (var) should be declared within the function itself unless there is a specific and necessary reason to do otherwise. Declaring everything outside the function makes them global variables and you shouldn’t ever do that unless it’s necessary, because it can cause conflicts with other parts of your program. When you start to code more and more e.g. beyond a page worth of lines, you’ll start to understand the wisdom of this guideline and readily apply it.

Otherwise your code is as good as anyone else’s minus the formatting which you should always do judiciously and clearly so it’s easy to read.

Have a great week Tony and congrats on finishing the Bonfire!! :slight_smile:

2 Likes

Thanks for your feedback Roger!
Keep in mind I did declare my variables inside the function - I omitted the first line:
function findLongestWord(str) {

…but it’s always good to be reminded (still a newbie).

cheers

1 Like

I wonder what’s the purpose of reg ex here? :thinking:

This solution involves multiple steps. First Reg Ex replace. 2nd Split. 3rd Sort. Clearly, inefficient.
But it works so keep it up! :slight_smile:

Here is how I’d do it.

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

EDIT: Another one

function findLongestWord(str) {
  return Math.max.apply(null, str.split(' ').map(w => w.length));
}

We are all newbies here my friend, it’s probably why unlike stackexchange we get very few d$ck responses and I for one am happier for it.

Thank for responding and good point, I didn’t realize as I just scanned the core of your code and didn’t think beyond that. Hahaha serves me right for being quick :wink:

1 Like

@adityaparab and @lbarjak can you guys go back and edit yours with detailed explanations? I mean it’s all sexy and stuff, but this is a learning platform and if you just post like this it’s more dick measuring than a learning experience for those of us who would love to learn from your awesomeness.

I can kind of figure out at least half, but I’m stumped on the others. Please and thank you!!! :slight_smile:

1 Like

True, overall very positive on here. I wouldn’t be on the forum otherwise.

1 Like

Oh you guys with your fancy arrow functions…hehe. I should learn to use them too.
On the other hand I think it’s wise to practice without until I’m comfortable with functions in general.

1 Like

Dear lbarjak;
Thanks for this piece. it has really broadened my knowledge.

1 Like