Linkify / Clickable Text-URLs但忽略那些已经包含在"a href"标签中的URL。

4
我正在使用jQuery开发一个链接脚本,其主要目的是将文本区域中的所有URL更改为可点击的链接,换句话说,就是在它们周围包装一个 a href 标签。实际上我使用的脚本运行良好,但当以“正确”的HTML方式添加链接时,问题开始出现,因为已经用 a href 标签包围了它们。请查看jsFiddle链接以查看我的脚本功能。例如,如果我在textarea中写入此内容:<a href=“http://google.com”>visualize.com</a> 它变成这样:<a href="<a href='http://google.com' target=‘_blank'>http://google.com</a>visualize.com</a> 当然它不起作用并搞乱了一切。如何仅对(http://www.)部分应用链接,并避免那些已经用 a href 标签包装的情况?
1个回答

3

看这里:

基本上,它首先解析标签之间的文本(但不包括<a>标签之间的文本),然后用链接正则表达式模式替换文本。

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/


嗨,安德鲁。它运行得很好,非常感谢您再次让我走上正确的轨道 :-) - Emil Devantie Brockdorff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接