Using the Twitter API I am trying to link any @ symbols to the persons account eg.
@stackoverflow
goes to https://twitter.com/stackoverflow
.
This is working well below except for when I am looking at Retweets which have the syntax
RT @stackoverflow:
The first regex works well but it keeps the : so I would like to remove the last character if it is a :
. How can I match the @stackoverflow
pattern but remove the :
from it. (I don’t want to remove the :
from the whole string as it may also have links in it)
var str = 'RT @stackoverflow: Great ...'
str = str.replace(/@(S*)/g, '<a target="_blank" href="https://twitter.com/$1">@$1</a>')
str = str.replace(/:$/,"") //doesn't do anything
console.log(str) // returns RT <a target="_blank" href="https://twitter.com/stackoverflow:">@stackoverflow:</a> Great ...
2
Answers
Instead of
/@(S*)/g
use/@(w+)/gi
, because Twitter usernames are exactly confined to whatw
represents:a-z
, and0-9
and_
. As stated in this Twitter support article:@trincot’s answer works well (I gave it a vote), but I am going to add my answer for anyone who encounters this and the
w
doesn’t fit their needs. For those who need to use theS
for any reason you can wrap the username in parenthesis to separate it out as a second back reference and then use that in the replace statement. In this case it would be$2
instead of$1
.