Skip to content

Instantly share code, notes, and snippets.

@anttih
Created February 4, 2010 18:34
Show Gist options
  • Save anttih/294958 to your computer and use it in GitHub Desktop.
Save anttih/294958 to your computer and use it in GitHub Desktop.
Code to replace URIs in a string with HTML anchors. Uses Grubers regex with some extra captures.
function hrefs2links(text) {
// Uses Grubers regex with some extra captures
var urire = /\b(?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|(www\d{0,3}[.]))((?:[^\s()<>]+|\([^\s()<>]+\))+(?:\([^\s()<>]+\)|[^`!()\[\]{};:'".,<>?«»“”‘’\s]))/g;
// replace URIs with HTML anchors
return text.replace(urire, '<a href="$&">$1$2</a>');
}
var text = hrefs2links("Check out http://example.com");
// text is 'Check out <a href="http://example.com">example.com</a>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment