Select the first 2 words with jQuery and wrap them with a <span> tag

How can I select the first two words in a sentence with jQuery, wrap them with a span tag and add the br tag after it?

Something like that:

<p><span>Lorem ipsum</span><br/> quosque tandem</p> 

But dynamically add the span and br tag.

I can only do this for the first word with this code:

 $('p').each(function(){ var featureTitle = $(this); featureTitle.html( featureTitle.text().replace(/(^\w+)/,'<span>$1</span><br/>') ); }); 

Thanks!!

+4
source share
2 answers
 $('p').html(function (i, html) { return html.replace(/(\w+\s\w+)/, '<span>$1</span><br/>') }); 

http://jsfiddle.net/crBJg/

+5
source

And for those who work with umlauts (ÀâΓ₯ΓΌ, etc.), you can use \S+\s\S+ instead of \w+\s\w+ to do this job properly.

See here fooobar.com/questions/1466727 / ...

0
source

All Articles