Link building in Javascript?

Is there an easy way to turn a string from

Then go to http:/example.com/ and foo the bar! 

in

 Then go to <a href="http://example.com">example.com</a> and foo the bar! 

in javascript on existing HTML page?

+6
javascript formatting text-parsing
source share
2 answers

Yes. The easiest way is to use regular expressions to replace things that look like a link for their related 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 a simple case. You should be careful with the script application here (for example, if I have http://"><script>doevil()</script> ). One way to get around this is to use the link building function:

 node.innerHTML = node.innerHTML.replace(/ ... /g, buildLink($1)); 

Where buildLink() can verify that the URL does not contain anything malicious.

However, the RegEx-innerHTML method will not work well on large text topics, as it breaks and restores all node HTML content. You can also achieve this with DOM methods:

  • Find link to node text
  • In the content, find the start and end indexes of the URL
  • Use the splitText() method to split the node into 3: before, link, after
  • Create a <a> node using href that matches the link
  • Use insertBefore() to insert this <a> node before the link
  • Use appendChild() to move the link in the <a> node
+7
source share

First of all, “inside an HTML page” is difficult because the “page” is actually a DOM tree (which consists partly of text nodes and mainly consists of HTML elements).

The easiest way to get closer to this problem is to target the content text nodes. For each node text, apply something like the following:

 // 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'); 

By the way: there are security implications. If you create links from unsterilized text, there is the possibility of XSS.

+3
source share

All Articles