开发者

Select last word in a container

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 a开发者_如何学Pythonchieve this.

Thanks in advance


<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)).


Try this:

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, then this will work. Otherwise, it won't, because it will replace all the previous elements with plain text.


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 />');
    });
});


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


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.


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>' ) );
} );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜