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!
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!
Share Improve this question asked Aug 25, 2017 at 5:05 user7308733user7308733 2- Possible duplicate of How do I retrieve all matches for a regular expression in JavaScript? – choasia Commented Aug 25, 2017 at 5:27
- 2 Read about regex capture groups. regular-expressions.info/brackets.html – Domino Commented Aug 25, 2017 at 5:53
3 Answers
Reset to default 6
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]);
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);
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"];