且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

选择容器中的最后一个单词

更新时间:2023-11-09 23:52:46

试试这个:

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

这是一个演示



如果div中的文本不包含任何div元素,那么这将有效。否则,它不会,因为它将用纯文本替换所有以前的元素。


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

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.