Create a gist now

Instantly share code, notes, and snippets.

Embed
AngularJS filter to create links out of URLs
app.filter('parseUrl', function() {
var //URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim,
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim,
//Change email addresses to mailto:: links.
replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
return function(text, target, otherProp) {
angular.forEach(text.match(replacePattern1), function(url) {
text = text.replace(replacePattern1, "<a href=\"$1\" target=\"_blank\">$1</a>");
});
angular.forEach(text.match(replacePattern2), function(url) {
text = text.replace(replacePattern2, "$1<a href=\"http://$2\" target=\"_blank\">$2</a>");
});
angular.forEach(text.match(replacePattern3), function(url) {
text = text.replace(replacePattern3, "<a href=\"mailto:$1\">$1</a>");
});
return text;
};
});
@char0n

This comment has been minimized.

Show comment
Hide comment
@char0n

char0n Oct 6, 2014

Seems to cause recursion. Doesn't work as expected.

char0n commented Oct 6, 2014

Seems to cause recursion. Doesn't work as expected.

@dmadisetti

This comment has been minimized.

Show comment
Hide comment
@dmadisetti

dmadisetti Dec 21, 2014

Produces nested tags when multiple links. Removing the forEachs does the trick since already global regexs

Produces nested tags when multiple links. Removing the forEachs does the trick since already global regexs

@geoidesic

This comment has been minimized.

Show comment
Hide comment
@geoidesic

geoidesic Sep 1, 2015

Doesn't work if you already have links in your string... then you again get double nested links. Needs a better regex.

Doesn't work if you already have links in your string... then you again get double nested links. Needs a better regex.

@JinBokLee

This comment has been minimized.

Show comment
Hide comment
@JinBokLee

JinBokLee Dec 7, 2015

Good

Good

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment