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

标签 jquery dynamic-links

所以我有一段看起来像这样的 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);
        }
    });
});

fiddle :http://jsfiddle.net/G8rKw/

编辑:这个版本效果更好:

$(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.*?>).]*?<\/a>)/gi, '<a href="">$1</a>');
            me.html(txt);
        }
    });
});

fiddle :http://jsfiddle.net/G8rKw/3/

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

$(document).ready(function() {
    var needle = 'hello';
    $('p').each(function() {
        var me = $(this),
        txt = me.html(),
        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);
        }
    });
});

fiddle :http://jsfiddle.net/webrocker/MtM3s/

关于jquery - 使用 jquery 或 JS 如何将字符串转换为链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12821244/

相关文章:

Jquery 时间微调器简化

javascript - 使用 Internet Explorer 11 时出现语法错误 'SCRIPT1002'

jquery - javascript隐藏两个元素并只显示一个

javascript - 如何在onClick函数的动态链接中传递参数

javascript - 选择此元素的第一个、第二个和第三个子元素

javascript - 旁边图片的 CSS 位置变化

php - 我如何生成用于邀请的动态 PHP 链接

android firebase动态链接PendingDynamicLinkData为null直接通过app

ios - 安装后 Firebase 动态链接不可用

c++ - 与 dlopen 的动态链接 : symbol not found