问题描述
|
我有以下网址:
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
。但是我还有其他一些页面,其中URL中也有“ 0”,而不仅仅是路径的开头。
正则表达式是什么样的?
解决方法
使用
window.location.pathname
检索当前路径(不包括
TLD)。
使用JavaScript字符串
match
法。
使用正则表达式/^\\/product\\/(\\d+)/
查找以/ product /开头的路径,然后找到一个或多个数字(在末尾添加i
以支持不区分大小写)。
提出这样的事情:
var res = window.location.pathname.match(/^\\/product\\/(\\d+)/);
if (res.length == 2) {
// use res[1] to get the id.
}
,/\\/product\\/(\\d+)/
,得到$1
。
,只是,作为一种选择,不用正则表达式即可执行此操作(尽管我承认正则表达式在这里非常好)
var url = \"http://test.example.com//mypage/1/test/test//test\";
var newurl = url.replace(\"http://\",\"\").split(\"/\");
for(i=0;i<newurl.length;i++) {
if(newurl[i] == \"\") {
newurl.splice(i,1); //this for loop takes care of situatiosn where there may be a // or /// instead of a /
}
}
alert(newurl[2]); //returns 1
,我想提出另一种选择。
.match(/\\/(\\d+)+[\\/]?/g)
这将返回id \的当前所有匹配项。
例:
var url = \'http://localhost:4000/#/trees/8/detail/3\';
// with slashes
var ids = url.match(/\\/(\\d+)+[\\/]?/g);
console.log(ids);
//without slashes
ids = url.match(/\\/(\\d+)+[\\/]?/g).map(id => id.replace(/\\//g,\'\'));
console.log(ids);