DannyBoy DannyBoy - 11 months ago 52
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:


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

such as:

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 Source

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);