PROWAREtech

articles » current » javascript » parse-internet-links-in-plain-text

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.

Remove scripts beforehand!

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:

Input Text
HTML Output

Result:



		
		
This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE