Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting hashtags out of a string.

If I had a string as such

var comment =  "Mmmm #yummy #donut at #CZ"

How can I get a list of hash tags that exist in the string variable?

I tried using JavaScript split() method but I have to keep splitting all strings created from the initial split string. Is there a simpler way of doing this?

like image 249
codeBarer Avatar asked Aug 28 '14 00:08

codeBarer


2 Answers

This will do it for anything with alphabetic characters, you can extend the regexp for other characters if you want:

myString.match(/#[a-z]+/gi);
like image 78
Keir Simmons Avatar answered Nov 09 '22 13:11

Keir Simmons


Just use a regular expression to find occurences of a hash followed by non-whitespace characters.

"Mmmm #yummy #donut at #CZ".match(/#\w+/g)
// evaluates to ["#yummy", "#donut", "#CZ"]
like image 20
Peter Olson Avatar answered Nov 09 '22 14:11

Peter Olson