2013-04-28 57 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(' '); 
} 

你可以改變這一點到另一個函數不延長的原型。