【问题标题】:Matching a substring匹配子串
【发布时间】:2021-03-26 17:50:28
【问题描述】:

我有这个网址/games/12345/stock

games/ 部分和 /stock 部分始终相同,但 12345 部分可能会改变

不是从 URL 接收此 URL,而只是作为 纯字符串

我想做的是我想要这样的东西

/alarms/${anything in here will match}/notifications.

我该怎么做?

【问题讨论】:

  • 您是在询问如何在快速处理程序中匹配此 url,还是一般而言如何匹配这样的字符串?
  • @eol 一般来说我怎么能匹配这样的字符串。
  • 你的 ${anything in here will match} 也可以包含'/'吗?如果没有,您可能对 string.split('/') 感到满意,并且不需要使用正则表达式。
  • 或者你可以使用 split() 函数。让parts = url.split('/stock');部分 = 部分[0].split('游戏/'); console.log(parts[1]);

标签: javascript node.js reactjs


【解决方案1】:

您可以使用正则表达式。创建一个静态部分包含动态 id 部分的模式。

然后,您可以在每个 url 上调用 match。第一个参数是静态 url,第二个参数是 id。

var route = "/games/:uid/stock";
var routeMatcher = new RegExp(route.replace(/:[^\s/]+/g, '([\\w-]+)'));
var url1 = "/games/12345/stock";
var url2 = "/games/333/stock";

console.log(url1.match(routeMatcher)[1])
console.log(url2.match(routeMatcher)[1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多