Regular expression for twitter username

This is the best solution I found yet to replace multiple occurrences of a twitter username.

The regex doing the trick is /(^|[^@\w])@(\w{1,15})\b/. I am catching what stand behind the @ character so I can replace the username correctly. And I am using global match flag (g) so it will replace all occurrences. asenovm answer is simple, but will not work in most user input contexts, as techexpert is explaining in his comment.

var output,
    text    = "@RayFranco is answering to @AnPel, this is a real '@username83' but this is [email protected], and this is a @probablyfaketwitterusername",
    regex   = /(^|[^@\w])@(\w{1,15})\b/g,
    replace = '$1<a href="http://twitter.com/$2">@$2</a>';

output = text.replace( regex, replace );

console.log ( output );

This is giving me what I expected (tested with node v0.9.1) :

@RayFranco is answering to @AnPel, this is a real '@username83' but this is [email protected], and this is a @probablyfaketwitterusername

This is based on Twitter "specs" for username :

Your username cannot be longer than 15 characters. Your real name can be longer (20 characters), but usernames are kept shorter for the sake of ease. 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.

Hope this helps.


A short an easy way to do it:

function validTwitteUser(sn) {
    return /^[a-zA-Z0-9_]{1,15}$/.test(sn);
}

This should do: ^@?(\w){1,15}$