Is there an simple way of turning a string from
Then go to http:/example.com/ and foo the bar!
into
Then go to <a href="http://example.com">example.com</a> and foo the bar!
in Javascript within an existing HTML page?
Create a hyperlink to a location on the webSelect the text or picture that you want to display as a hyperlink. Press Ctrl+K. You can also right-click the text or picture and click Link on the shortcut menu. In the Insert Hyperlink box, type or paste your link in the Address box.
Yes. The simplest way is to use a regular expressions to substitute things that look like a link for their linked equivalents. Something like:
node.innerHTML = node.innerHTML.replace(/(http:\/\/[^\s]+)/g, "<a href='$1'>$1</a>")
(my RegEx is a little rusty, so you may need to play with the syntax). This is just a simple case. You need to be wary of script injection here (for example if I have http://"><script>doevil()</script>
). One way to work around this is by using a link building function:
node.innerHTML = node.innerHTML.replace(/ ... /g, buildLink($1));
Where buildLink()
can check to make sure the URL doesn't contain anything malicious.
However, the RegEx-innerHTML method will not perform very well on large bodies of text though, since it tears down and rebuilds the entire HTML content of the node. You can achieve this with DOM methods as well:
splitText()
method to split the node into 3: before, link, after<a>
node with the href
that's the same as the linkinsertBefore()
to insert this <a>
node before the linkappendChild()
to move the link into the <a>
nodeFirst, "within an HTML page" is difficult because a "page" is actually a DOM tree (which is partially composed of text nodes and mostly composed of HTML elements).
The easiest way to approach this problem would be to target content-rich text nodes. For each text node, apply something like this:
// we'll assume this is the string of a content-rich text node
var textNode = document.getElementById('contentNode');
textNode.innerHTML = textNode.innerHTML.replace(/(\s)(http:\/\/[^\s]+)(\s)/g, '$1<a href="$2">$2</a>$3');
BTW: there are security implications here. If you generate links from unsterilized text, there is the possibility of XSS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With