【发布时间】:2017-10-10 06:43:36
【问题描述】:
我有一个名称为 "foo[biz][bar]" 的输入。获得最后一部分的优雅方式是什么,即"bar"?我可以使用 jQuery 和 lodash 库。
【问题讨论】:
-
"foo[biz][bar]".split('[').pop().slice(0,-1)
标签: javascript jquery lodash
我有一个名称为 "foo[biz][bar]" 的输入。获得最后一部分的优雅方式是什么,即"bar"?我可以使用 jQuery 和 lodash 库。
【问题讨论】:
"foo[biz][bar]".split('[').pop().slice(0,-1)
标签: javascript jquery lodash
你可以使用正则表达式 /\[(.*?)\]/g 来获取括号之间的所有匹配项,然后获取最后一个匹配项(如果有):
str = "foo[biz][bar]"
matches = str.match(/\[(.*?)\]/g)
if (matches.length) console.log(matches[matches.length - 1])
// based on answer above group override but without `(?:` non capturing group
console.log( /(\[(\w+)\])+/g.exec(str).pop() )
由Debuggex创建
【讨论】:
/\[(.*)\]/g 时我得到"[biz][bar]"。 ? 在 /\[(.*?)\]/g 中做了什么,它将先前的结果分成两部分? ? 的意思是“零或一”?
与@loretoparisi 相同,但会覆盖组。
str = "foo[biz][bar]"
matches = /(?:\[(\w+)\])+/g.exec(str)
console.log(matches.pop())
【讨论】: