正则表达式在url中找到id

Pee*_*Haa 7 javascript regex match

我有以下网址:

http://example.com/product/1/something/another-thing

虽然它也可以是:

http://test.example.com/product/1/something/another-thing

要么

HTTP://completelydifferentdomain.tdl/product/1/something/another-thing

我想使用Javascript从URL中获取数字1(id).

唯一总是一样的是/product.但是我还有一些其他页面,其中/producturl中也有不在路径的开头.

正则表达式是什么样的?

Mat*_*att 11

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

  2. 使用JavaScript字符串 match方法.

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

  4. 想出这样的事情:

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


rid*_*rid 5

/\/product\/(\d+)/并获得$1.