I am using the function below to match URLs inside a given text and replace them for HTML links. The regular expression is working great, but currently I am only replacing t
Made some optimizations to Travis' Linkify()
code above. I also fixed a bug where email addresses with subdomain type formats would not be matched (i.e. example@domain.co.uk).
In addition, I changed the implementation to prototype the String
class so that items can be matched like so:
var text = 'address@example.com';
text.linkify();
'http://stackoverflow.com/'.linkify();
Anyway, here's the script:
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, '$&')
.replace(pseudoUrlPattern, '$1$2')
.replace(emailAddressPattern, '$&');
};
}