Created
June 10, 2013 09:14
-
-
Save karmiphuc/5747456 to your computer and use it in GitHub Desktop.
To auto-magically parse different types of links within a text string. We will look at standard URL links, links applied to Twitter usernames and those applied to Hashtags.
@author http://www.simonwhatley.co.uk/parsing-twitter-usernames-hashtags-and-urls-with-javascript
@link http://www.simonwhatley.co.uk/examples/twitter/prototype/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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-_:%&~\?\/.=]+/g, 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-_]+/g, 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-_]+/g, 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, #javascript and parsing hashtags as URLs"; | |
document.writeln(test.parseHashtag()); | |
// Demo 4. Cascading methods | |
var test = "@whatterz is writing a blog post about #twitter and #javascript, which can be found at http://www.simonwhatley.co.uk/examples/twitter/prototype and http://www.simonwhatley.co.uk/parsing-twitter-usernames-hashtags-and-urls-with-javascript /cc @simonwhatley"; | |
document.writeln(test.parseURL().parseUsername().parseHashtag()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment