且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式在url中找到id

更新时间:2023-02-21 07:41:16


  1. 使用 window.location.pathname
    检索当前路径(不包括
    TLD)。

  1. Use window.location.pathname to retrieve the current path (excluding TLD).

使用JavaScript字符串
match method。

Use the JavaScript string match method.

使用正则表达式 / ^ \ / product \ /(\d +)/ 查找以/开头的路径product /,然后是一个或多个数字(最后添加 i 以支持不区分大小写)。

Use the regex /^\/product\/(\d+)/ to find a path which starts with /product/, then one or more digits (add i right at the end to support case insensitivity).

想出这样的事情:

var res = window.location.pathname.match(/^\/product\/(\d+)/);
if (res.length == 2) {
    // use res[1] to get the id.
}