最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Select last word in a container - Stack Overflow

matteradmin3PV0评论

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

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

Share Improve this question edited Aug 16, 2011 at 8:29 Reporter 3,9485 gold badges35 silver badges49 bronze badges asked Aug 16, 2011 at 8:21 Lee PriceLee Price 5,21211 gold badges35 silver badges36 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 3

<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./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>' ) );
} );
Post a comment

comment list (0)

  1. No comments so far