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

Javascript jQuery是给定字符的第一个和最后一个,javascript,jquery,Javascript,Jquery,我试图能够在span元素中选择给定字符的第一个和最后一个实例 e、 g hello(我是hello) 我希望能够找到此范围内的第一个括号和最后一个括号,并为它们附加一个类,以便输出可能是: <span class="foo">hello <span class="bar">(this is hello)</span></span> hello(我是hello) 这可能吗?我在jQuery中首先查看了,,但它似乎只适用于选择元素而不是字符。您可

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

e、 g

hello(我是hello)
我希望能够找到此范围内的第一个括号和最后一个括号,并为它们附加一个类,以便输出可能是:

<span class="foo">hello <span class="bar">(this is hello)</span></span>
hello(我是hello)
这可能吗?我在jQuery中首先查看了
,但它似乎只适用于选择元素而不是字符。

您可以使用正则表达式:

$('.foo').html(function(_, html){
     return html.replace(/\((.*)\)/, '<span class="bar">($1)</span>')
});
$('.foo').html(函数(\ux,html){
返回html.replace(/\(.*)/,“($1)”
});
(单击“使用JS运行”)

如果要处理多个带括号的组,请使用

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

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

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

你能为你所使用的
函数(u,html){
提供文档吗?它只是一个变量名,我可以使用
html(函数(I,html)
,但我喜欢对未使用的变量使用
var firstE = "Hello, Ben!".indexOf('e'); // firstE = 1
var lastE = "Hello, Ben!".lastIndexOf('e'); //lastE = 8