Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

javascript - 仅在指定字符的第一个实例上分割字符串(split string only on first instance of specified character)

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]; Takes good_luck and provides me with luck .(注意到good_luck并为我提供了luck 。) Works great!(很棒!) But, now I have a class that looks like good_luck_buddy .(但是,现在我有一个看起来像good_luck_buddy的类。) How do I get my javascript to ignore the second _ and give me luck_buddy ?(如何获取我的JavaScript来忽略第二个_并给我luck_buddy ?) I found this var field = element.split(new char [] {'_'}, 2);(我发现这个var field = element.split(new char [] {'_'}, 2);) in ac# stackoverflow answer but it doesn't work.(在ac#stackoverflow答案中,但不起作用。) I tried it over at jsFiddle...(我在jsFiddle上尝试过...)   ask by Ofeargall translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use capturing parentheses :(使用捕获括号 :)

"good_luck_buddy".split(/_(.+)/)[1] "luck_buddy" They are defined as(它们被定义为) If separator contains capturing parentheses, matched results are returned in the array.(如果separator包含捕获括号,则在数组中返回匹配的结果。) So in this case we want to split at _.+ (ie split separator being a sub string starting with _ ) but also let the result contain some part of our separator (ie everything after _ ).(因此,在这种情况下,我们要在_.+处进行拆分(即,拆分分隔符是以_开头的子字符串) ,还要让结果包含分隔符的某些部分(即_之后的所有内容 )。) In this example our separator (matching _(.+) ) is _luck_buddy and the captured group (within the separator) is lucky_buddy .(在此示例中,我们的分隔符(匹配_(.+) )是_luck_buddy ,而捕获的组(在分隔符内)是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.(如果没有捕获括号,则luck_buddy (匹配.+ )将不会包含在结果数组中,因为简单split的情况就是结果中不包含分隔符。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...