user7308733
user7308733

Reputation:

Filter all hashtags found in string

I need to create an array with all the hashtags contained in a string. For example:

Testing #nature #love#instacool#anothertogether #likeforlike, #relax.

multi-line... #festival--

some more text #aaa \n#anotherhashtag

The result would be:

["nature", "love", "instacool", "anothertogether", "likeforlike", "relax", "festival", "aaa", "anotherhashtag"]

What should be the REGEX for this case? I tried some that I found on the internet but none worked in the given example.

Upvotes: 1

Views: 861

Answers (3)

Dmitry Ragozin
Dmitry Ragozin

Reputation: 75

You need to use RegExp#exec. Use the next solution:

var str = "Testing #nature #love#instacool#anothertogether #likeforlike, #relax. \n multi-line... #festival-- \nsome more text #aaa \n#anotherhashtag";
var re = /#(\w+)/g;
var res = [];
while (var buf = re.exec(str)) {
  res.push(buf[1]);
}
console.log(res);

Upvotes: 1

In the flag mg, m means ‘Multiline’, g means ‘Global search’.

`Testing #nature #love#instacool#anothertogether #likeforlike, #relax.

multi-line... #festival--

some more text #aaa \n#anotherhashtag`.match(/#\w+/mg).map(s => s.substr(1))

Upvotes: 1

kind user
kind user

Reputation: 41893

Use following approach:

var str = 'Testing #nature #love#instacool#anothertogether #likeforlike, #relax. \nmulti-line... #festival-- some more text #aaa \n#anotherhashtag';

console.log(str.match(/#\w+/g).map(v => v.replace('#', '')));

Upvotes: 4

Related Questions