Select the last word in the container

I'm just wondering if there is a way to select the last word in the DIV. I don't think there is any obvious way to do this, so is there any work around?

I am not opposed to using CSS or Javascript to achieve this.

Thanks in advance

+5
source share
6 answers

Try the following:

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

Here is a demo

If the text inside the div does not contain any div element, this will work. Otherwise, this will not happen, because it will replace all previous elements with plain text.

+2
source

<div>or no <div>, it comes down to basic string manipulation (using the method match()).

var words = $('#your_div').text().match(/(\w+)/g);
if (words.length) {
    var last_word = words[words.length - 1];
}

, match(), (var last_word = words[words.length - 1];), (if (words.length)).

+3

, ( 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 />');
    });
});
+1

, Javascript HTML DOM div, ( ) .

0

:

: 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! span, ( ):

$( document ).ready( function() {
    theWords = $( '#theWords' ).html();
    lastWord = getLastWord( theWords );
    appendCon = '#lastWord';
    $( appendCon) .append( $( '<span> '+lastWord+'</span>' ) );
} );
0

.

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 + '&nbsp;<strong>' + lastPart + '</strong>'; //join first part and last part and put the required html for the last word
0

All Articles