Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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

Something like this:

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

But add the span and br tag dynamically.

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

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

Thanks!!

like image 440
amp511 Avatar asked Mar 03 '13 03:03

amp511


2 Answers

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

http://jsfiddle.net/crBJg/

like image 174
undefined Avatar answered Oct 23 '22 19:10

undefined


And for those who are working with umlauts (äöåü etc.), you might want to use \S+\s\S+ instead of \w+\s\w+ to make this work properly.

See here https://stackoverflow.com/a/12845431/5349534

like image 35
Twoch Avatar answered Oct 23 '22 19:10

Twoch