1

I want to add <"a"> to every word inside an <"h3">. The link should contain the word it has been wrapped around. The web page has many different h3's.

<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!

Algatella
  • 33
  • 8

2 Answers2

2
  1. You can use html() with callback function to update the value

  2. For updating it with anchor tag use replace() with regex

$('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

$('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>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

The code from the given answer won't work well with embedded tags and Unicode words.

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>
VisioN
  • 143,310
  • 32
  • 282
  • 281