查找文本字符串中的最后一个单词并用HTML包装

时间:2013-04-28 02:58:06

标签: javascript jquery html

我有一个文本字符串,例如:

<div id="ideal">The quick brown fox jumps over the lazy Stack Overflow user</div>

我想在HTML中包含最后一个字('user')来生成:

<div id="ideal">
     The quick brown fox jumps over the lazy 
     Stack Overflow <span class="foo">user</span>
</div>

到目前为止,我已经使用空格分割字符串并查看替换匹配,但大多数解决方案使用正则表达式,但正则表达式可能是在字符串中的其他位置重复的单词。

我目前使用子字符串进行以下工作:

var original = document.getElementById("ideal").textContent;

var para = original.split(" ");
var paracount = para.length;
var wordtoreplace = para[paracount-1];

var idx = original.lastIndexOf(wordtoreplace);
var newStr = original.substring(0, idx) + '<span class="foo">' + wordtoreplace + '</span>';

但这仅适用于使用纯JavaScript而不是<div class="ideal">

的许多实例中的可重复功能

是否有一种可重复的方式使用javascript或jQuery(通过类而不是id)对<div class="ideal">的一个或多个实例执行此操作?

5 个答案:

答案 0 :(得分:7)

你可以这样做:

$('.ideal').each(function() {
    var $this = $(this);
    $this.html($this.html().replace(/(\S+)\s*$/, '<span class="foo">$1</span>'));
});

The working demo.

答案 1 :(得分:1)

您可以将您的逻辑放入函数中,例如wrapLast,并使用JQuery.each以“.ideal”迭代所有匹配的元素。

$(".ideal").each(function(idx, node){
    wrapLast($(node));
});

我在jsiddle

上放了一个简单的例子

答案 2 :(得分:1)

您需要拆分文本,抓取最后一个元素,完成工作并重新加入阵列。

var text = $('#ideal').text();
var arrText = text.split(' ');
var arrLength = arrText.length

arrText[arrLength-1] = '<span class="foo">' + arrText[arrLength-1] + '</span>';

$('#ideal').html(arrText.join(' '));

工作示例:http://jsfiddle.net/sKZCa/1/

答案 3 :(得分:1)

如果您不反对扩展原型并将使用它,这是一个很好的方法。

http://jsbin.com/esimed/1/edit

Element.prototype.wrapLastWord = function (left, right) {
  var words = this.innerHTML.split(' ');
  var lastWord = words[words.length - 1];
  words[words.length - 1] = left + lastWord + right;
  this.innerHTML = words.join(' ');
}

您可以将其更改为另一个不扩展原型的功能。

答案 4 :(得分:0)

这是一种非常简单的手动方式,有更好的方法,但它有效。

步骤:将字符串拆分为数组,查找数组长度并减去1以获取最后一个元素(b / c从0开始),然后将它们全部重新连接在一起。

var strarr = array();
var str = 'The quick brown fox jumps over the lazy Stack Overflow user';
strarr = str.split(' ');

// the -1 accounts for array starting at 0
var wheremylastoneat = strarr.length - 1;

// adds the class to the contents of the last element of the array
strarr[wheremylastoneat] = '<span class="foo">'+strarr[strarrlen]+'</span>';

// puts the pieces back together
str = strarr.join();