最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Extract all hashtags from string without # - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

3 Answers 3

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"];
发布评论

评论列表(0)

  1. 暂无评论