0

I'm new to JS, tried using -

/[0-9a-z]+$/gi
/[^0-9a-z]+$/gi

neither worked. Can anyone tell me where I am going wrong?

4
  • 1
    The second one looks fine. Can you show us an example of how it's "not working"? Commented Aug 31, 2012 at 15:06
  • What do you mean by "neither worked"? 1. what where you trying to do? 2. what was the expected result ? 3. and most importantly: what happened instead? Commented Aug 31, 2012 at 15:08
  • 1
    try /\W{0,}/g, and try starting to accept some answers people give you. Commented Aug 31, 2012 at 15:09
  • I'm trying to find longest word in a string. A word qualifies as a group of letters and numbers, without any spaces in between. If I use ' ' instead of the regex, I get a fine solution. Here's the JSFiddle Commented Aug 31, 2012 at 15:11

1 Answer 1

1

Replace

var sentence_split = arr.split(/[0-9a-z]+$/gi);

with

var sentence_split = arr.split(/[^0-9a-z]+/gi);

... if you prefer to go this way.

Explanation: the original regex was anchored (with $) to the end of the string, and splitted by words - and not symbols separating them.

Still, there's more than one way to do the things you do: I'd probably go just with:

var words = sentence.match(/(\w+)/g);

... capturing sequences of word-consisting symbols instead of splitting the phrase by something that separates them. Here's a Fiddle to play with.

UPDATE: And one last thing. I felt a bit... uneasy about wasting sort just to get max essentially. I don't know if you share these thoughts, still here's how I would update the searching code:

var longest;
words.forEach(function(e) {
  if (! longest || longest.length < e.length) {
    longest = e;
  }
});

It's forEach, because I'm a bit lazy and imagine having a luxury of NOT working with IE8-; still, it's quite easy to rewrite this into a regular for... array-walking routine.

Updated fiddle.

Sign up to request clarification or add additional context in comments.

4 Comments

Works! Thanks! Could you explain why?
BTW, it can be useful to console.log the array as well (as I did in my example to illustrate what would be captured).
I do use console.log regularly.. EDIT. Could you help me change the code to for...? I have no clue how to... Just a few hints would help.
@Namanyayg Check forEach documentation page at MDN. It'll be helpful both for understanding its usage and possible ways of replacing it. )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.