Last active
September 17, 2018 12:02
-
-
Save Alanaktion/c58dec9c3b568b0c5443d72895afb56a to your computer and use it in GitHub Desktop.
Replace URLs with links via JS
This file contains 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
/** | |
* 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