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

Pau*_*oag 7 jquery dynamic-links

所以我有一段看起来像这样的HTML ......

<p>This is some copy. In this copy is the word hello</p>
Run Code Online (Sandbox Code Playgroud)

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

<p>This is some copy. In this copy is the word <a href="">hello</a></p>
Run Code Online (Sandbox Code Playgroud)

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

<p>In this copy is the <a href="">word hello</a></p>
Run Code Online (Sandbox Code Playgroud)

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

<p>In this copy is the <a href="">word <a href="">hello</a></a></p>
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激.

Dav*_*irk 0

在将单词变成链接之前,是否可以不测试该单词的父元素?

if (parent != 'a') {
   // do your thing
}
Run Code Online (Sandbox Code Playgroud)

(我不知道实际的 jQuery 会是什么来测试这个)

编辑

<p>以下内容将替换所有不包含链接的元素中的单词。

可能无法完全按照要求工作,但希望能为您指明方向

// get all p elements that contain the word hello but DO NOT have link in them
var elems = $('p:contains("hello")').not(':has(a)');


// replace instances of hello in the selected p elements
$(elems).html($(elems).html().replace(/(hello)/g,'<a href="new">$1</a>'));
Run Code Online (Sandbox Code Playgroud)

JSBin 上的现场演示