Skip to content Skip to sidebar Skip to footer

In Javascript, How Can I Get The "tags" Of A String Into An Array?

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

Solution 1:

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 "#"

Post a Comment for "In Javascript, How Can I Get The "tags" Of A String Into An Array?"