1
The quick brown #fox jumped over the #reallyBigFence.

The result should be: ['fox','reallyBigFence']

All tags are spaceless and they start with the hash tag.

I'm new to regex, but I think this would work (not sure): /#([a-z0-9]+)/gi

What do I do with that regex? .match?

1 Answer 1

2

Yes, just .match():

var resultarray = "The quick brown #fox jumped over the #reallyBigFence."
   .match(/#([a-z0-9]+)/gi);

The match method will return an array of found substrings (because the regexp has the global flag), otherwise null if nothing is found. Yet, it returns the full matching string and not the capturing groups so the above will result in ["#fox","#reallyBigFence"]. As JavaScript does not know Lookbehind, you will need to fix it afterwards with

if (resultarray) // !== null
    for (var i=0; i<resultarray.length; i++)
        resultarray[i] = resultarray[i].substr(1); // remove leading "#"
Sign up to request clarification or add additional context in comments.

3 Comments

It might be better to use /#([^\s]+)/ or /#(\w+)/ as the valid characters in a word may include hyphens and other characters not in a-z0-9.
@RobG /#(\w+)/ is getting only #lazy here "...jumped over the #lazy-dog"
Yes, \w matches word characters, RegExp doesn't think hyphens belong in words. :-( I was just pointing out that you'll need to play with the pattern to get what you want since you haven't defined it explicitly. Perhaps /#([\w-]+)/g or similar.

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.