Parsing Twitter Usernames, Hashtags and URLs with JavaScript
Demo 1. Parsing URLs
String.prototype.parseURL = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
return url.link(url);
});
};
test = "Simon Whatley's online musings can be found at: http://www.simonwhatley.co.uk";
document.writeln(test.parseURL());
Demo 2. Parsing Twitter Usernames
String.prototype.parseUsername = function() {
return this.replace(/[@]+[A-Za-z0-9-_]+/, function(u) {
var username = u.replace("@","")
return u.link("http://twitter.com/"+username);
});
};
test = "@whatterz is writing a post about JavaScript";
document.writeln(test.parseUsername());
Demo 3. Parsing Twitter Hashtags
String.prototype.parseHashtag = function() {
return this.replace(/[#]+[A-Za-z0-9-_]+/, function(t) {
var tag = t.replace("#","%23")
return t.link("http://search.twitter.com/search?q="+tag);
});
};
test = "Simon is writing a post about #twitter and parsing hashtags as URLs";
document.writeln(test.parseHashtag());
Demo 4. Cascading methods
var test = "@whatterz is writing a blog post about #twitter, which can be found at http://www.simonwhatley.co.uk";
document.writeln(test.parseURL().parseUsername().parseHashtag());