DannyBoy DannyBoy - 1 month ago 11
Javascript Question

How to get words start with # in an string

I am trying to read the hashtags in the browsers and check if two specific hashes exists.
Here is an example:

#world#player3#track1


So I want to check if the above string contains hashtags
player
or
track
, and if so, then it should return the those hashtags.

such as:
player3
and
track1


I tried to achieve it with the following code but its not working:

var str = "#player1#track2"
if (str.length > 0 && str.indexOf("player") >= 0) {
var player = str.substr(str.indexOf("player"), str.indexOf("#"));
var track = str.substr(str.indexOf("track"), str.indexOf("#"));
console.log(player + "" + track);
};


Any ideas how to achieve that?

Answer

Use a regular expression to match the hashtag prefix followed by any digits.

var str = "#player1#track2"
var player = str.match(/#player\d+/);
player = player ? player[0] : "";
var track = str.match(/#track\d+/);
track = track ? track[0] : "";
console.log(player + track);