Skip to content

Instantly share code, notes, and snippets.

@Alanaktion
Last active September 17, 2018 12:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alanaktion/c58dec9c3b568b0c5443d72895afb56a to your computer and use it in GitHub Desktop.
Save Alanaktion/c58dec9c3b568b0c5443d72895afb56a to your computer and use it in GitHub Desktop.
Replace URLs with links via JS
/**
* Replace URLs with hyperlinks in an element
*
* @param {string} selector
* @return {void}
*/
var linkReplace = function(selector) {
var element = document.querySelector(selector);
var text = element.innerHTML;
text = text.replace(/(https?:\/\/|www\.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g, function(match) {
var result = '<a href="';
if (match.substr(0, 4) != 'http') {
result += 'http://';
}
result += match + '" target="_blank" rel="nofollow noopener noreferrer">' + match + '</a>';
return result;
});
element.innerHTML = text;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment