在我的代码中,我基于_分割字符串并获取数组中的第二项。

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

带来好运,给我带来好运。工作好了!

但是,现在我有了一个看起来像good_luck_buddy的类。我如何让我的javascript忽略第二个_,给我luck_buddy?

我找到了var field = element。Split (new char [] {'_'}, 2);在c# stackoverflow中回答,但它不起作用。我尝试在jsFiddle…


当前回答

这应该很快

函数splitOnFirst (str, sep) { const index = str.indexOf(sep); 返回索引< 0 ?[str]: [str.slice(0, index), str.slice(index + sep.length)]; } console.log (splitOnFirst(“good_luck”、“_”)[1]) console.log (splitOnFirst(“good_luck_buddy”、“_”)[1])

其他回答

这适用于我的Chrome + FF:

"foo=bar=beer".split(/^[^=]+=/)[1] // "bar=beer"
"foo==".split(/^[^=]+=/)[1] // "="
"foo=".split(/^[^=]+=/)[1] // ""
"foo".split(/^[^=]+=/)[1] // undefined

如果你也需要钥匙,试试这个:

"foo=bar=beer".split(/^([^=]+)=/) // Array [ "", "foo", "bar=beer" ]
"foo==".split(/^([^=]+)=/) // [ "", "foo", "=" ]
"foo=".split(/^([^=]+)=/) // [ "", "foo", "" ]
"foo".split(/^([^=]+)=/) // [ "foo" ]

//[0] = ignored (holds the string when there's no =, empty otherwise)
//[1] = hold the key (if any)
//[2] = hold the value (if any)

对于像我这样不习惯正则表达式的初学者来说,这个解决方案是有效的:

   var field = "Good_Luck_Buddy";
   var newString = field.slice( field.indexOf("_")+1 );

slice()方法提取字符串的一部分并返回一个新字符串,indexOf()方法返回字符串中指定值第一次出现的位置。

这个解决方案对我很有效

var str = "good_luck_buddy";
var index = str.indexOf('_');
var arr = [str.slice(0, index), str.slice(index + 1)];

//arr[0] = "good"
//arr[1] = "luck_buddy"

OR

var str = "good_luck_buddy";
var index = str.indexOf('_');
var [first, second] = [str.slice(0, index), str.slice(index + 1)];

//first = "good"
//second = "luck_buddy"

Mark F的解决方案很棒,但旧的浏览器不支持。Kennebec的解决方案很棒,老浏览器也支持,但不支持regex。

所以,如果你正在寻找一个解决方案,只分割你的字符串一次,这是由旧浏览器支持和支持regex,这是我的解决方案:

String.prototype.splitOnce = function(正则表达式) { Var match = this.match(正则表达式); 如果(匹配) { var match = this.indexOf(match[0]); [这返回。substring (0, match_i), 这一点。Substring (match_i + match[0].length)]; } 其他的 {返回[这个,""];} } Var STR = "某事/////另一件事///再次"; 警报(str.splitOnce (/ \ / + /) [1]);

你也可以使用非贪婪匹配,它只是一个简单的行:

A = "good_luck_buddy" Const [,g,b] = a.match(/(.*?)_(.*)/) console.log (g,“也”,b)