简体   繁体   中英

Convert text list of urls into clickable HTML links

I'm looking to convert a text list of urls into clickable links.

<!DOCTYPE html>

<body>  
<script>

// http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/

%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
}

var a1 = document.getElementById("test").innerHTML;
var a2 = replaceURLWithHTMLLinks(a1);
document.getElementById("test").innerHTML = a2;

</script>

<div id="test">
http://www.site.com/
http://www.site2.com/
http://www.site3.com/
</div>

</body>
</html>

Firebug returns the list of sites in the console for:

document.getElementById("test").innerHTML;

ie:
www.site.com/
www.site2.com/
www.site3.com/

Why do I get this error for the line below?

var a1 = document.getElementById("test").innerHTML;

TypeError: document.getElementById(...) is null

That is because you are trying to access the element before it has been added so document.getElementById('test') return null. You can wrap it under window.onload or add the script after the html element.

Try:

<script>

// http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/

%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
}

window.onload = function(){
  var elm =  document.getElementById("test");
  var modifiedHtml = replaceURLWithHTMLLinks(elm.innerHTML);
  elm.innerHTML = modifiedHtml ;
}

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM