user3776241
user3776241

Reputation: 543

Regex to match mentions and hashtags in Twitter

I have this JS right here:

return text.replace(/@([a-z\d_]+)/ig, '<a
href="?r=site/twitterprofile&q=$1">@$1</a>');

It gets all of the Twitter mentions, and outputs the link for each. In this same function, I want to combine this pattern to get all of the hashtags:

/\S*#\S+/gi

How do I combine these two into one pattern?

Upvotes: 1

Views: 1792

Answers (2)

Ramin eghbalian
Ramin eghbalian

Reputation: 2667

regex for match hashtags:

\(#[a-zA-Z\d_-]+)/ig

regex for match mentions:

/(^|)(@[a-zA-Z0-9\d-]+)/ig

regex for URLs:

/(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z09+&@#\/%=~_|])/img

i, m, g are regex options

i option means : insensitive => Case insensitive match.
m option means : global => Don't return after first match, find all matches.
g option means : multi line => ^ and $ match start/end of line.

Upvotes: 0

Pointy
Pointy

Reputation: 413727

You can take advantage of the fact that the .replace() function lets you pass in a function to return a replacement string:

return text.replace(/([@#])([a-z\d_]+)/ig, function(_, marker, tag) {
  if (marker === "@")
    return '<a href="?r=site/twitterprofile&q=$1">' + tag + '</a>';
  return "Hashtag: " + tag;
});

That looks for things that look like either @ tags or hashtags, and then decides which sort of replacement to return. When you pass a function to .replace(), the function is called such that the first argument (ignored in the sample above) is the entire match. The second and subsequent arguments contain the grouped sub-matches, corresponding to $1, $2, etc when you use a simple string replacement. Thus the first group is the @ or # character, and the second is the matched text.

Upvotes: 1

Related Questions