Reputation:
I'm extracting hashtags from strings like this:
const mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa';
const hashtags = mystring.match(/#\w+/g) || [];
console.log(hashtags);
The output is:
['#arebaba', '#ole', '#cool', '#aaa']
How my regex should be so that the match is:
['arebaba', 'ole', 'cool', 'aaa']
I don't want to use map function!
Upvotes: 3
Views: 1857
Reputation: 5
You can use the Positive Lookbehind option:
(?<=...)
Ensures that the given pattern will match, ending at the current position in the expression. The pattern must have a fixed width. Does not consume any characters.
For example given the string 'foobar', the regex (?<=foo)bar
would match bar
only.
Or in this case (crating an array of word tags):
const mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa';
const hashtags = mystring.match(/(?<=#)\w+/g) || [];
// ["arebaba","ole","cool","aaa"];
Upvotes: 0
Reputation: 2882
const mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa';
var regexp = /#(\w+)/g;
var match = regexp.exec(mystring);
while (match != null){
console.log(match[1])
match = regexp.exec(mystring)
}
EDIT The code can be shortened. However, it's not your regex that will solve your problem, but picking the correct method.
var mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa',
match;
var regexp = /#(\w+)/g;
while (match = regexp.exec(mystring))
console.log(match[1]);
Upvotes: 6
Reputation: 626738
You already matched multiple substrings and you know there is #
in front, so just remove it:
const mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa';
const hashtags = mystring.match(/#\w+/g).map(x => x.substr(1)) || [];
console.log(hashtags);
Upvotes: 2