skip to Main Content

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


  1. Instead of /@(S*)/g use /@(w+)/gi, because Twitter usernames are exactly confined to what w represents: a-z, and 0-9 and _. As stated in this Twitter support article:

    A username can only contain alphanumeric characters (letters A-Z, numbers 0-9) with the exception of underscores, as noted above. Check to make sure your desired username doesn’t contain any symbols, dashes, or spaces.

    var str = 'RT @stackoverflow: Great ...'
    
    str = str.replace(/@(w+)/gi, '<a target="_blank" href="https://twitter.com/$1">@$1</a>')
    	
    console.log(str) 
    Login or Signup to reply.
  2. @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 the S 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.

    var str = 'RT @stackoverflow: Great ...'
    str = str.replace(/@((S*):)/g, '<a target="_blank" href="https://twitter.com/$2">@$1</a>')
    str = str.replace(/:$/,"") //doesn't do anything
    console.log(str)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search