正则表达式在url中找到id [英] Regex to find id in url

查看:792
本文介绍了正则表达式在url中找到id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下网址:

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)。

And I want to get the number 1 (id) from the URL using Javascript.

唯一一个始终是同样是 / product 。但我还有一些其他网页,其中的网址中还有 / product ,而不是在路径的开头。

The only thing that would always be the same is /product. But I have some other pages where there is also /product in the url just not at the start of the path.

正则表达式是什么样的?

What would the regex look like?

推荐答案


  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.
}


这篇关于正则表达式在url中找到id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆