Linkify/可点击的文本URL,但忽略那些已经包含在"a href"中的文本URL [英] Linkify / Clickable Text-URLs but ignore those already wrapped in "a href"'s

查看:93
本文介绍了Linkify/可点击的文本URL,但忽略那些已经包含在"a href"中的文本URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery中的链接化脚本,其唯一目的是获取文本区域中的所有URL,并将其更改为可点击的链接,换句话说,在它们周围包裹一个a href标记.

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.

我正在使用的脚本实际上可以正常工作,但是当以正确" HTML方式添加链接并在其周围加上a href标记时,问题就开始了.
请转到 jsFiddle 链接,以查看我的脚本正在运行.

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.

例如,如果我在文本区域中写以下内容:<a href=http://google.com>visualize.com</a>,它将变成:<a href="<a href='http://google.com' target=‘_blank'>http://google.com</a>visualize.com</a>哪一个原因不起作用并将所有内容弄乱了.

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.

我如何仅在部分( http:// www.)上应用链接,而不能将链接包装在标签?

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?

推荐答案

查看此内容:

基本上,它首先解析标记之间(而不是< 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/

这篇关于Linkify/可点击的文本URL,但忽略那些已经包含在"a href"中的文本URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆