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

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…


当前回答

如果你正在寻找一种更现代的方式来做这件事:

let raw = "good_luck_buddy"

raw.split("_")
    .filter((part, index) => index !== 0)
    .join("_")

其他回答

这适用于我的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 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"

我不惜一切代价避免RegExp。还有一件事你可以做:

"good_luck_buddy".split('_').slice(1).join('_')

你需要正则表达式和数组做什么?

myString = myString.substring(myString.indexOf('_')+1)

你好! 我的弦=我的弦。 控制台日志(myString)。

ES6中获取字符串中第一个键和其余部分的简单方法是:

 const [key, ...rest] = "good_luck_buddy".split('_')
 const value = rest.join('_')
 console.log(key, value) // good, luck_buddy