2013-05-05 129 views
0

我試圖能夠選擇span元素中給定字符的第一個和最後一個實例。jQuery給定字符的第一個和最後一個字符

例如

<span class="foo">hello (this is hello)</span> 

我希望能夠找到這個範圍內,在第一架和最後一個托架,並附加類裏面,這樣的輸出可能是:

<span class="foo">hello <span class="bar">(this is hello)</span></span> 

這可能嗎?我在jQuery中看過first,但它似乎只適用於選擇元素而不是字符。

回答

1

您可以使用正則表達式:

$('.foo').html(function(_, html){ 
    return html.replace(/\((.*)\)/, '<span class="bar">($1)</span>') 
}); 

Demonstration如果要處理超過一個bracked組(點擊「與JS運行)

,使用

$('.foo').html(function(_, html){ 
    return html.replace(/\(([^\)]*)\)/g, '<span class="bar">($1)</span>') 
}); 
+0

您能提供該函數的文檔嗎(_,html){'您使用過嗎? – acdcjunior 2013-05-05 18:59:33

+0

這是[這個來自jQuery](http://api.jquery.com/html/)。 '_'只是一個變量名,我可以使用'html(function(i,html)',但我喜歡用'_'作爲未使用的變量。 – 2013-05-05 19:11:43

0

的Javascript爲此提供了本地方法,字符串有一個indexOf()方法,該方法返回給定字符串或字符的第一個實例的位置以及一個lastIndexOf()方法返回最後一個實例。例如:

var firstE = "Hello, Ben!".indexOf('e'); // firstE = 1 
var lastE = "Hello, Ben!".lastIndexOf('e'); //lastE = 8 
相關問題