【问题标题】:Linkify / Clickable Text-URLs but ignore those already wrapped in "a href"'sLinkify / Clickable Text-URLs 但忽略那些已经包含在“a href”中的
【发布时间】:2013-12-06 09:08:50
【问题描述】:

我正在使用 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.)上应用链接,而不是链接已经包含在 @987654326 中的那些情况@标签?

【问题讨论】:

    标签: javascript jquery linkify


    【解决方案1】:

    看这个:

    基本上它首先解析出标签之间的文本(而不是之间),然后用链接正则表达式模式替换txt。

    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/

    【讨论】:

    • 你好安德鲁。效果很好,非常感谢你让我再次走上正轨:-)
    猜你喜欢
    • 2016-02-04
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多