Reputation: 5212
I was just wondering if there is a way to select the last WORD in a DIV. I don't think there is any obvious way to do this, so are there any work arounds?
I don't mind using CSS or Javascript to achieve this.
Thanks in advance
Upvotes: 5
Views: 4962
Reputation: 92
This works.
var text = 'Lorem Ipsum Dolor Sit Amet';
var textSplit = text.split(' ');//split the text with space characters
var lastPart = textSplit.pop(); // retrieve the last word from the string
var firstPart = textSplit.join(' '); // retriece the words except the last word
var result = firstPart + ' <strong>' + lastPart + '</strong>'; //join first part and last part and put the required html for the last word
Upvotes: 1
Reputation:
Here's my solution to this question:
Demo: http://wecodesign.com/demos/stackoverflow-7075397.htm
function getLastWord( words ) {
lastWord = words.split( ' ' ).pop();
return lastWord;
}
$( document ).ready( function() {
theWords = $( '#theWords' ).html();
lastWord = getLastWord( theWords );
$( '#lastWord' ).html( lastWord );
} );
SCOPE CREEP! Given the new requirements to dynamically inject the span tag, I've modified the code as follows (I've also updated my demo):
$( document ).ready( function() {
theWords = $( '#theWords' ).html();
lastWord = getLastWord( theWords );
appendCon = '#lastWord';
$( appendCon) .append( $( '<span> '+lastWord+'</span>' ) );
} );
Upvotes: 0
Reputation: 45589
Try this:
var $div = $('div');
$div.html($div.text().replace(/(\w+?)$/, '<span>$1</span>'));
If the text inside the div does not contain any div element, then this will work. Otherwise, it won't, because it will replace all the previous elements with plain text.
Upvotes: 2
Reputation: 38121
If you are after another regular expression based solution, you could try (uses jQuery):
$(function() {
$('div').each(function() {
var $div = $(this);
var text = $div.text(); // get the text of everything inside the div
// the next line gets the last word followed only by non-word characters in that text
// NB: the [\s\S] trick is to match any character, *including* new lines
var last_word = $.trim(text).replace(/^[\s\S]*\b(\w+)\b[\W]*$/i, '$1');
// this is from a jsFiddle I tried to post to test it.
$('#output').append($div.attr('id') + ': Last word = ' + last_word + '<br />');
});
});
Upvotes: 1
Reputation: 75317
<div>
or no <div>
, it boils down to basic String manipulation (using the match()
) method.
var words = $('#your_div').text().match(/(\w+)/g);
if (words.length) {
var last_word = words[words.length - 1];
}
We build an array of all words using the match()
method, and then get the last one (var last_word = words[words.length - 1];
), but only if some words were found (if (words.length)
).
Upvotes: 3
Reputation: 1264
You could probably use Javascript and HTML DOM to access the content of the div and then simply split the string (with a space as separator) and take the last split part.
Upvotes: 0