2013-04-28 56 views
1

我有一个文本字符串,例如:找到最后一个字,敷在HTML

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

我想在HTML包裹硬道理(“用户”)制作:

<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">的一个或多个实例?

+1

为什么不使用该代码创建函数并将元素传递给该函数? – plalx 2013-04-28 03:08:28

回答

6

一个简单的例子,你可以做这样的事情:

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

The working demo.

+1

+1我正要发布相同的东西......只是略有不同:http://jsfiddle.net/Mottie/wCvT2/ – Mottie 2013-04-28 03:13:55

+0

光和短。爱它! – 2015-10-19 18:26:15

1

你可以把你的逻辑放入一个函数,比如wrapLast,并使用JQuery.each来迭代所有匹配的元素,使用“.ideal”。

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

我把jsiddle

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(); 
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/

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

你可以改变这一点到另一个函数不延长的原型。