ronnie burns
ronnie burns

Reputation: 230

javascript: span around last two words in string

Using javascript, I'm trying to insert a span around the last 2 words of a string.

Using the below regular expression I can get the last word, but I can't figure out how to get the last 2 words.

var $div = $('div');
$div.html($div.text().replace(/(\w+?)$/, '<span>$1</span>'));

Upvotes: 1

Views: 1466

Answers (3)

Richard Hamilton
Richard Hamilton

Reputation: 26434

Break the text down into words and use the slice method to find all words except the last two, and the last two words.

var words = $div.text().split(' ');

$div.html(words.slice(0, words.length - 2).join(' ') + " " + "<span class='bold'>" + 
words.slice(words.length-2, words.length).join(' ') + "</span>");

Fiddle: http://jsfiddle.net/rjs4gac1/

Upvotes: 4

&#193;ngela
&#193;ngela

Reputation: 1425

You need to check for another word \w+ and a whitespace character (or more) \s+ between them:

$div.html($div.text().replace(/(\w+\s+\w+?)$/, '<span>$1</span>'));

Upvotes: 0

Shawn Mehan
Shawn Mehan

Reputation: 4568

You need a second \w separated by a space, so

$div.html($div.text().replace(/(\w+\s\w+?)$/, '<span>$1</span>'));

if you can have multiple spaces, make that optional

$div.html($div.text().replace(/(\w+\s+\w+?)$/, '<span>$1</span>'));

Upvotes: 3

Related Questions