jQuery给定字符的第一个和最后一个字符

jQuery给定字符的第一个和最后一个字符

问题描述:

我试图能够选择span元素中给定字符的第一个和最后一个实例。jQuery给定字符的第一个和最后一个字符

例如

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

我希望能够找到这个范围内,在第一架和最后一个托架,并附加类里面,这样的输出可能是:

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

这可能吗?我在jQuery中看过first,但它似乎只适用于选择元素而不是字符。

您可以使用正则表达式:

$('.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

的Javascript为此提供了本地方法,字符串有一个indexOf()方法,该方法返回给定字符串或字符的第一个实例的位置以及一个lastIndexOf()方法返回最后一个实例。例如:

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