【问题标题】:RegExp to match query parameters in url [duplicate]正则表达式匹配 url 中的查询参数 [重复]
【发布时间】:2018-06-28 12:28:12
【问题描述】:

我已将查询参数格式从 &Key=Value 更改为 /Key/Value。

现在我正在尝试使用正则表达式在 url 中解析它们。不知道我做错了什么,但这是我的代码

示例网址路径:http://localhost/MyApp/#!/Page1/SubPage1/SubPage2/Key/value-example

let re = new RegExp(`^.*/(Key)/([a-zA-Z0-9]+).*$`);
while (match = re.exec(url)) {
    params[match[1]] = match[2];
}

它以无限循环结束

我做错了什么?

【问题讨论】:

  • 它以无限循环结束,因为您没有使用g 修饰符编译正则表达式。正则表达式索引不是高级的,while 总是从字符串开始。另外,如果值中有-,则添加-let re = new RegExp(`^.*/(Key)/([a-zA-Z0-9-]+).*$`, "g");。但是,如果您不希望有多个匹配项,只需将while 替换为if,则可以在没有gnew RegExp(`^.*/(Key)/([a-zA-Z0-9-]+).*$`) 的情况下使用正则表达式。
  • 反正已经解释了很多次了,以stackoverflow.com/questions/31969913/…结尾为骗人的理由。

标签: javascript regex typescript


【解决方案1】:

我建议使用split(),而不是使用正则表达式。

var url = 'http://localhost/MyApp/#!/Page1/SubPage1/SubPage2/Key/value-example'
var keyName = 'Key'
var urlParts = url.split('/')
var keyIndex = urlParts.indexOf(keyName) // "Key" is at index #8
// Since the value appears right after the key, we can access it by increasing the index by 1
var value = urlParts[keyIndex + 1] // "value-example" is at index #9

这里是命令url.split('/')的结果:

[ 'http:',
  '',
  'localhost',
  'MyApp',
  '#!',
  'Page1',
  'SubPage1',
  'SubPage2',
  'Key',
  'value-example' ]

所以我们要做的是在数组中定位所需键的索引并查看下一个值 - index+1。

【讨论】:

    猜你喜欢
    • 2017-12-01
    • 2015-09-27
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2020-12-19
    相关资源
    最近更新 更多