PROWAREtech
JavaScript: Parse Internet Links in Plain Text
Use Regex to parse Internet links in plain text and convert to HTML anchor elements.
This simple code will convert links contained in plain text to HTML anchors. This code should be run on the client side, freeing server resources.
function createAnchorHTML(link) {
var a = document.createElement("a");
a.target = "_blank"; // NOTE: can remove or change the target here
a.href = link;
a.appendChild(document.createTextNode(link));
return a.outerHTML;
}
var text = "This is a link http://test.com that will be parsed. This is another link https://www.test.com/?q=query%201&p=0123456789 that will be parsed."
var linkRegex = /(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
var html = text.replace(linkRegex, createAnchorHTML("$1"));
console.log(html);
alert(html);
Enter text with Hyper-text Transfer Protocol (HTTP) or Hyper-text Transfer Protocol Secure (HTTPS) links to see how they are parsed:
Result:
Comment