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

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…


当前回答

我需要字符串的两个部分,所以,regex lookbehind帮助我这个。

const full_name = 'Maria do Bairro'; Const [first_name, last_name] = full_name.split(/(?<=^[^]+) /); console.log (first_name); console.log (last_name);

其他回答

这适用于我的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 arr = element.split(/_(.*)/)

您可以使用第二个参数,它指定分割的限制。 即: Var字段=元素。分割(' _ ',1)[1];

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

let raw = "good_luck_buddy"

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

我需要字符串的两个部分,所以,regex lookbehind帮助我这个。

const full_name = 'Maria do Bairro'; Const [first_name, last_name] = full_name.split(/(?<=^[^]+) /); console.log (first_name); console.log (last_name);

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

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

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