Search code examples
javascriptjquerylinkify

Linkify / Clickable Text-URLs but ignore those already wrapped in "a href"'s


I’m working on a linkification script in jQuery which sole purpose is to take all the URLs in a textarea and change it to clickable links, in other words, to wrap a a href tag around them.

The script that I’m using actually works fine but the problem starts when a link is added the “correct” HTML way, with the a href tag around them.
Please go to the jsFiddle link to see my script in action.

For example, if I write this in my textarea: <a href=“http://google.com”>visualize.com</a> it become: <a href="<a href='http://google.com' target=‘_blank'>http://google.com</a>visualize.com</a> which of cause does not work and mess everything up.

How do I apply the linkification only on the parts (http:// and www.) and NOT those cases where the link is already wrapped in a a href tag?


Solution

  • See this:

    Basically it parse out the text between tags(but not between <a>) firstly, and then replace the txt with link regex patterns.

    function replaceTxtNotInA(html, regex, replace) {
    
        //just to make the txt parse easily, without (start) or (ends) issue
        html = '>' + html + '<';
    
        //parse txt between > and < but not follow with</a
        html = html.replace(/>([^<>]+)(?!<\/a)</g, function(match, txt) {
    
            //now replace the txt
            return '>' + txt.replace(regex, replace) + '<';
        });
    
        //remove the head > and tail <
        return html.substring(1, html.length - 1);
    }
    

    http://jsfiddle.net/rooseve/4qa5Z/1/