简体   繁体   English

添加<a>到里面的每个单词</a> <h3>

[英]Add <a> to every word inside <h3>

I want to add <"a"> to every word inside an <"h3">. 我想在<“h3”>中的每个单词中添加<“a”>。 The link should contain the word it has been wrapped around. 该链接应包含它已被包裹的单词。 The web page has many different h3's. 该网页有许多不同的h3。

<h3>add links</h3>
<h3>to each word</h3>

The result should look like this: 结果应如下所示:

<h3><a href="add">add</a> <a href="links">links</a></h3>
<h3><a href="to">to</a> <a href="each">each</a> <a href="word">word</a></h3>

I don't know if it's possible (or good) to use PHP else jQuery/JS would be good! 我不知道是否可能(或好)使用PHP其他jQuery / JS会很好!

  1. You can use html() with callback function to update the value 您可以使用html()函数的html()来更新值

  2. For updating it with anchor tag use replace() with regex 要使用锚标记更新它,请使用带有regex replace()

 $('h3').html(function(i, v) { return v.replace(/(\\s*)(\\w+)(\\s*)/g, '$1<a href="$2">$2</a>$3'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h3>add links</h3> <h3>to each word</h3> 

To avoid encoded html entities try this code 要避免编码的html实体,请尝试此代码

 $('h3').html(function() { return $(this).text().replace(/(\\s*)(\\w+)(\\s*)/g, '$1<a href="$2">$2</a>$3'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h3>add links</h3> <h3>to each word</h3> 

The code from the given answer won't work well with embedded tags and Unicode words. 给定答案的代码不适用于嵌入式标签和Unicode字。

Here is a better fool-proof alternative: 这是一个更好的万无一失的替代品:

 $('h3').contents().filter(function() { return this.nodeType === 3; }).replaceWith(function() { return this.nodeValue.replace(/(\\S+)(?=\\s+|$)/g, '<a href="$&">$&</a>'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h3>add links to each word</h3> <h3>with Юникод support & <i>ignoring</i> <em>this</em></h3> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM