微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用jquery或JS如何将字符串转换为链接?

所以我有一段看起来像这样的 HTML ……
<p>This is some copy. In this copy is the word hello</p>

我想使用jquery将单词hello转换为链接.

<p>This is some copy. In this copy is the word <a href="">hello</a></p>

这本身并不太难.我的问题是,如果这个词已经是一个链接,如下面的例子…

<p>In this copy is the <a href="">word hello</a></p>

我不希望最终在链接中找到链接

<p>In this copy is the <a href="">word <a href="">hello</a></a></p>

任何帮助将非常感激.

解决方法

一个小正则表达式应该做的伎俩(更新,见下文):
$(document).ready(function(){
    var needle = 'hello';
    $('p').each(function(){
        var me = $(this),txt = me.html(),found = me.find(needle).length;
        if (found != -1) {
            txt = txt.replace(/(hello)(?!.*?<\/a>)/gi,'<a href="">$1</a>');
            me.html(txt);
        }
    });
});

小提琴:http://jsfiddle.net/G8rKw/

编辑:此版本更好:

$(document).ready(function() {
    var needle = 'hello';
    $('p').each(function() {
        var me = $(this),found = me.find(needle).length;
        if (found != -1) {
            txt = txt.replace(/(hello)(?![^(<a.*?>).]*?<\/a>)/gi,'<a href="">$1</a>');
            me.html(txt);
        }
    });
});

小提琴:http://jsfiddle.net/G8rKw/3/

再次编辑:这次,“hello”作为变量传递给正则表达式

$(document).ready(function() {
    var needle = 'hello';
    $('p').each(function() {
        var me = $(this),found = me.find(needle).length,regex = new RegExp('(' + needle + ')(?![^(<a.*?>).]*?<\/a>)','gi');
        if (found != -1) {
            txt = txt.replace(regex,'<a href="">$1</a>');
            me.html(txt);
        }
    });
});

小提琴:http://jsfiddle.net/webrocker/MtM3s/

原文地址:https://www.jb51.cc/jquery/177166.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐