Reputation: 1657
I wanted to find all h2 tags on a page and then wrap first two words in a span tag. I have checked this stackoverflow question, but it didn't help me.
I am able to do as per this link and dd span to first 2 words, but the only issue is that if I have html inside h2 tag for eg I have hyperlink inside h2 tag.
Can anyone please help me how to make this code so as html is ignored and only first two words are considered?
Any help is really appreciated!
jQuery(document).ready(function($){
jQuery('h2').html(function (i, html) {
return html.replace(/(\w+\s\w+)/, '<span>$1</span>')
});
});
<h2>
<a title="test post 2" href="#">
test text dolor sit enum
</a>
</h2>
<h2>lorem ipsum dolor sit enum</h2>
Upvotes: 1
Views: 1242
Reputation: 861
use JQuery
to get the text within the HTML, then use text()
and match
to find the first 2 words, and finally replace that text in the HTML wrapping it with <span>
:
$(document).ready(function($){
$('h2').html(function (i, html) {
var text = $($.parseHTML(html)).text().match(/\w+\s\w+/)[0];
return html.replace(text, '<span>'+text+'</span>');;
});
});
https://jsfiddle.net/j4fd86aw/6/
Upvotes: 0
Reputation: 538
This should work for you.
jQuery(document).ready(function($){
jQuery('h2').html(function (i, html) {
if(/<[a-z][\s\S]*>/i.test(html)) {
html = jQuery.parseHTML(html);
return html[0].innerHTML.replace(/(\w+\s\w+)/, '<span>$1</span>');
}
return html.replace(/(\w+\s\w+)/, '<span>$1</span>');
});
});
h2 {
color:#f2f2f2;
}
h2 span {
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2><a title="test post 2" href="#">test text dolor sit enum</a></h2>
<h2>lorem ipsum dolor sit enum</h2>
Upvotes: 2
Reputation: 252
var h2 = $('h2').html().split(' ');
$('span').html(h2[0] + ' ' + h2[1]);
Upvotes: 0
Reputation: 1347
$(function(){
var h2 = $('h2 > a').html();
alert(h2.replace(/(\w+\s\w+)/, '<span>$1</span>'));
});
https://jsfiddle.net/y3llowjack3t/jornvLee/3/
Upvotes: 0
Reputation: 5020
Use the text()
function:
jQuery(document).ready(function($){
jQuery('h2').text(function (i, txt) {
console.log ( txt.replace(/(\w+\s\w+)/, '<span>$1</span>'))
});
});
See here: https://jsfiddle.net/spdthfgx/
Upvotes: 0