【问题标题】:JavaScript - elegant way to find last part "foo[biz][bar]"JavaScript - 找到最后一部分“foo [biz] [bar]”的优雅方式
【发布时间】:2017-10-10 06:43:36
【问题描述】:

我有一个名称为 "foo[biz][bar]" 的输入。获得最后一部分的优雅方式是什么,即"bar"?我可以使用 jQuery 和 lodash 库。

【问题讨论】:

  • "foo[biz][bar]".split('[').pop().slice(0,-1)

标签: javascript jquery lodash


【解决方案1】:

你可以使用正则表达式 /\[(.*?)\]/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() )

正则表达式/\[(.*?)\]/g解释:

正则表达式/(\[(\w+)\])+/g解释:

Debuggex创建

【讨论】:

  • 你能解释一下这个模式是如何工作的吗?我明白为什么当模式为/\[(.*)\]/g 时我得到"[biz][bar]"?/\[(.*?)\]/g 中做了什么,它将先前的结果分成两部分? ? 的意思是“零或一”?
  • 我也添加了解释。
【解决方案2】:

与@loretoparisi 相同,但会覆盖组。

str = "foo[biz][bar]"
matches = /(?:\[(\w+)\])+/g.exec(str)
console.log(matches.pop())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-25
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 2010-10-12
    相关资源
    最近更新 更多