Friday, March 22, 2013

Linkify all URLs that appear in a paticular div

Many times we come accross situation that our webpage contains urls but we
forget to give links to it at the time of uploading.
Now here is a simple javascript code that we can give at body load and it will search all urls in page and give them links.

<script>function linkify(text){
    if (text) {
        text = text.replace(
   /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
            function(url){
                var full_url = url;
                if (!full_url.match('^https?:\/\/')) {
                    full_url = 'http://' + full_url;
                }
                return '<a href="' + full_url + '">' + url + '</a>';
            }
        );
    }
        document.getElementById("hi").innerHTML = text;
}</script>

<body onload="linkify(document.getElementById('hi').innerHTML)"> 

Note: here "hi" is the div that contains text to be converted into links.

No comments :

Post a Comment