Reputation: 357
Does anybody know whether this can be achieved in jQuery. Target/addClass to the last word of an element, in this case the word 'Text' within a h1 tag. Bear in mind I know I can target the last word with a span tag but I'm working with a CMS that has something like %My_heading% markup. (not exactly but I'm hoping this is understood)
<h1>Some Heading Text</h1>
Upvotes: 1
Views: 3988
Reputation: 87073
$('h1').html(function(index, curHTML) {
var text = curHTML.split(/[\s-]/),
newtext = '<span class="some">' + text.pop() + '</span>';
return text.join(' ').concat(' ' + newtext);
});
Upvotes: 2
Reputation: 100195
Do you mean:
var txt = $("h1").text();
var splitted = txt.split(" ");
var lastWord = splitted.pop();
var newTxt = splitted.join(" ") + "<span class='someclass'> " + lastWord + "</span>";
console.log(newTxt);
Fiddle: http://jsfiddle.net/7qUb6/
Upvotes: 1
Reputation: 145438
If you need to add class to the last word, you anyway need to surround it with a tag.
One of the easiest ways to do it is using regular expression:
$("h1").html(function(index, old) {
return old.replace(/(\b\w+)$/, '<span class="myClass">$1</span>');
});
DEMO: http://jsfiddle.net/Dy4vh/
Upvotes: 4
Reputation: 76890
Something like
//Split the string into words
var last_arr = $('h1').text().split(' ');
//Get the last one
var last = last_arr[last_arr.length - 1];
fiddle http://jsfiddle.net/KZFX4/
Upvotes: 1