user930026
user930026

Reputation: 1657

Select first two words of h2 tag and wrap in span tag

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>

Upvotes: 1

Views: 1242

Answers (5)

Andr&#233;s Esguerra
Andr&#233;s Esguerra

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

Maverick976
Maverick976

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

Marvin Medeiros
Marvin Medeiros

Reputation: 252

var h2 = $('h2').html().split(' ');
$('span').html(h2[0] + ' ' + h2[1]);

Upvotes: 0

Devnsyde
Devnsyde

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

Johannes Jander
Johannes Jander

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

Related Questions