5

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!!

amp511
  • 131
  • 2
  • 11

2 Answers2

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

http://jsfiddle.net/crBJg/

Ram
  • 143,282
  • 16
  • 168
  • 197
1

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

Community
  • 1
  • 1
Twoch
  • 168
  • 5