Regex How To Replace Twitter Links
Please help me with regular expression. I found this good peace of code: var ify = function() { return { 'link': function(t) { return t.replace(/(^|\s+)
Solution 1:
function processTweetLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
text = text.replace(exp, "<a href='$1' target='_blank'>$1</a>");
exp = /(^|\s)#(\w+)/g;
text = text.replace(exp, "$1<a href='http://search.twitter.com/search?q=%23$2' target='_blank'>#$2</a>");
exp = /(^|\s)@(\w+)/g;
text = text.replace(exp, "$1<a href='http://www.twitter.com/$2' target='_blank'>@$2</a>");
return text;
}
Solution 2:
Here's my code to do that:
functionaddTwitterLinks(text) {
return text.replace(/[\@\#]([a-zA-z0-9_]*)/g,
function(m,m1) {
var t = '<a href="http://twitter.com/';
if(m.charAt(0) == '#')
t += 'hashtag/';
return t + encodeURI(m1) + '" target="_blank">' + m + '</a>';
});
}
And here's a demo of it in action: http://siliconsparrow.com/javascripttwittertest.html
Solution 3:
The regex starts with /(^|\s+)
, this means it matches @foo
only when it is at the start of the document or when it is preceded by a space.
Then the regex only matches for letters, numbers and underscores.
Maybe you should make the matching less strict, and match for a series of characters that is not a space, like \@(!\s){1,15}\s
, although I'm not sure if those unicode characters are even allowed in Twitter names. Lots of documents mention just [A-Za-z0-9]. Is this changed?
Post a Comment for "Regex How To Replace Twitter Links"