1

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!


My Fiddle :

JSFiddle


My JS :

jQuery(document).ready(function($){ 
    jQuery('h2').html(function (i, html) {
        return html.replace(/(\w+\s\w+)/, '<span>$1</span>')
    });
});

My HTML :

<h2>
    <a title="test post 2" href="#">
        test text dolor sit enum
    </a>
</h2>
<h2>lorem ipsum dolor sit enum</h2>
Community
  • 1
  • 1
user930026
  • 1,647
  • 5
  • 34
  • 59

5 Answers5

2

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>
Maverick976
  • 528
  • 1
  • 4
  • 11
0

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/

Johannes Jander
  • 4,974
  • 2
  • 31
  • 46
0
$(function(){
    var h2 = $('h2 > a').html();
    alert(h2.replace(/(\w+\s\w+)/, '<span>$1</span>'));
});

https://jsfiddle.net/y3llowjack3t/jornvLee/3/

Devnsyde
  • 1,297
  • 1
  • 13
  • 34
0
var h2 = $('h2').html().split(' ');
$('span').html(h2[0] + ' ' + h2[1]);
Marvin Medeiros
  • 202
  • 4
  • 22
0

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/

Andrés Esguerra
  • 849
  • 5
  • 15