Autolink, jQuery plugin to detect URLs in text and make them into clickable links

March 16, 2016 24 Yehor Rykhnov

An example of a simple jQuery script to search for URL on the page and turning them into clickable links (<a>....</a>).

Task

I need a script that will replace the URLs on the page and turn them into html links (<a></a>). If URL has tag of link <a> then do nothing. URL can begin with http, https or ftp. URL may contain Latin or Cyrillic characters.

Solution

Code of plugin:

jQuery(function($) {
    var re = /((http|https|ftp):\/\/[a-zа-я0-9\w?=&.\/-;#~%-]+(?![a-zа-я0-9\w\s?&.\/;#~%"=-]*>))/g;
    function makeHTML(textNode) {
        var source = textNode.data;
        return source.replace(re, function() {
            var url = arguments[0];
            var a = $('<a></a>').attr({'onclick' : 'window.open(\'' + url + '\'); return false;','href': '#', 'target': '_blank'}).text(url);
            return url.match(/^https?:\/\/$/) ? url : $('<div></div>').append(a).html();
        });
    };
    function eachText(node, callback) {
        $.each(node.childNodes, function() {
            if (this.nodeType != 8 && this.nodeName != 'A') {
                this.nodeType != 1 ? callback(this) : eachText(this, callback);
            }
        });
    };
    $.fn.autolink = function() {
        return this.each(function() {
            var queue = [];
            eachText(this, function(e) {
                var html = makeHTML(e);
                if (html != e.data) {
                    queue.push([e, makeHTML(e)]);
                }
            });
            $.each(queue, function(i, x) {
                $(x[0]).replaceWith(x[1]);
            });
        });
    };
});

Save this code in the js file, for example autolink.js

How to use

Example:

<!DOCTYPE html>
<html>
    <head>
        <title>autolink test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script type="text/javascript" src="autolink.js"></script>
        <script>
            jQuery(function ($) {
                $('.content').autolink();
            });
        </script>
    </head>
    <body>
        <div class="content">
            <p>Test: http://devreadwrite.com/</p>
            <p>Тест: http://кодер.укр/</p>
        </div>
    </body>
</html>

AutoCorrect on all page:

jQuery(function ($) {
    $('document.body').autolink();
});

Download

GitHub: https://github.com/egor/jquery-autolink.git


urljQuery