仅在指定字符的第一个实例上拆分字符串

问题描述:

在我的代码中,我根据 _ 拆分了一个字符串,然后抓住数组中的第二项。

In my code I split a string based on _ and grab the second item in the array.

var element = $(this).attr('class');
var field = element.split('_')[1];

取得 good_luck 并为我提供运气。效果很棒!

Takes good_luck and provides me with luck. Works great!

但是,现在我的课程看起来像 good_luck_buddy 。如何让我的javascript忽略第二个 _ 并给我 luck_buddy

But, now I have a class that looks like good_luck_buddy. How do I get my javascript to ignore the second _ and give me luck_buddy?

我在ac#stackoverflow回答中找到了这个 var field = element.split(new char [] {'_'},2); 但是它不起作用。我在jsFiddle试了一下...

I found this var field = element.split(new char [] {'_'}, 2); in a c# stackoverflow answer but it doesn't work. I tried it over at jsFiddle...

使用捕获括号

"good_luck_buddy".split(/_(.+)/)[1]
"luck_buddy"

它们定义为


如果分隔符包含捕获括号,匹配的结果是数组中返回的

If separator contains capturing parentheses, matched results are returned in the array.

所以在这种情况下我们要分割为 _。+ (即拆分分隔符是以 _ 开头的子字符串)让结果包含我们分隔符的一部分(即所有 _ 之后)。

So in this case we want to split at _.+ (i.e. split separator being a sub string starting with _) but also let the result contain some part of our separator (i.e. everything after _).

在此示例中,我们的分隔符(匹配 _(。+))是 _luck_buddy 和捕获的组(在分隔符内)是 lucky_buddy 。如果没有捕获括号, luck_buddy (匹配。+ )将不会包含在结果数组中,因为它是使用简单 split 的情况,结果中不包含分隔符。

In this example our separator (matching _(.+)) is _luck_buddy and the captured group (within the separator) is lucky_buddy. Without the capturing parenthesis the luck_buddy (matching .+) would've not been included in the result array as it is the case with simple split that separators are not included in the result.