正则表达式在url中找到id [英] Regex to find id in url
问题描述
我有以下网址:
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?
推荐答案
-
使用
window.location.pathname
到
检索当前路径(不包括
TLD)。
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屋!