如何解决正则表达式可在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)。 唯一始终相同的是/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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。