我试图能够在 span 元素中选择给定字符的第一个和最后一个实例。
例如
<span class="foo">hello (this is hello)</span>
我希望能够在此范围内找到第一个括号和最后一个括号并将它们附加一个类,因此输出可能是:
<span class="foo">hello <span class="bar">(this is hello)</span></span>
这可能吗?我看过firstjQuery,但它似乎只适用于选择元素而不是字符。
我试图能够在 span 元素中选择给定字符的第一个和最后一个实例。
例如
<span class="foo">hello (this is hello)</span>
我希望能够在此范围内找到第一个括号和最后一个括号并将它们附加一个类,因此输出可能是:
<span class="foo">hello <span class="bar">(this is hello)</span></span>
这可能吗?我看过firstjQuery,但它似乎只适用于选择元素而不是字符。
您可以使用正则表达式:
$('.foo').html(function(_, html){
return html.replace(/\((.*)\)/, '<span class="bar">($1)</span>')
});
演示(点击“用 JS 运行”)
如果您想处理多个支架组,请使用
$('.foo').html(function(_, html){
return html.replace(/\(([^\)]*)\)/g, '<span class="bar">($1)</span>')
});
Javascript为此提供了本机方法。字符串有一个indexOf()返回给定字符串或字符的第一个实例的位置的lastIndexOf()方法和一个返回最后一个实例的方法。例如:
var firstE = "Hello, Ben!".indexOf('e'); // firstE = 1
var lastE = "Hello, Ben!".lastIndexOf('e'); //lastE = 8