且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Linkify/可点击的文本URL,但忽略那些已经包含在"a href"中的文本URL

更新时间:2023-11-27 12:27:04

查看此内容:

基本上,它首先解析标记之间(而不是< a>之间)的文本,然后使用链接正则表达式模式替换txt.

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/