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

浪尽此生 提交于 2020-01-11 09:47:08

问题


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?


回答1:


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/



来源:https://stackoverflow.com/questions/20419989/linkify-clickable-text-urls-but-ignore-those-already-wrapped-in-a-hrefs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!