Created
December 20, 2011 12:17
-
-
Save codeincontext/1501387 to your computer and use it in GitHub Desktop.
Linkify urls in a JS string
This file contains hidden or 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
// I didn't do this. This guy did: http://stackoverflow.com/a/7123542/288660 | |
if(!String.linkify) { | |
String.prototype.linkify = function() { | |
// http://, https://, ftp:// | |
var urlPattern = /\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim; | |
// www. sans http:// or https:// | |
var pseudoUrlPattern = /(^|[^\/])(www\.[\S]+(\b|$))/gim; | |
// Email addresses | |
var emailAddressPattern = /\w+@[a-zA-Z_]+?(?:\.[a-zA-Z]{2,6})+/gim; | |
return this | |
.replace(urlPattern, '<a href="$&">$&</a>') | |
.replace(pseudoUrlPattern, '$1<a href="http://$2">$2</a>') | |
.replace(emailAddressPattern, '<a href="mailto:$&">$&</a>'); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment