Javascript 要在url中查找id的正则表达式
我有以下网址: 虽然它也可以是: 或 我想使用Javascript从URL中获取数字1(id) 唯一不变的是Javascript 要在url中查找id的正则表达式,javascript,regex,match,Javascript,Regex,Match,我有以下网址: 虽然它也可以是: 或 我想使用Javascript从URL中获取数字1(id) 唯一不变的是/product。但是我还有一些其他页面,url中也有/product,只是不在路径的开头 正则表达式看起来像什么?/\/product\/(\d+)/并获得$1 习惯于 检索当前路径(不包括 TLD) 使用JavaScript字符串 方法 使用正则表达式/^\/product\/(\d+)/查找以/product/开头的路径,然后查找一个或多个数字(在末尾添加i以支持区分大小写)
/product
。但是我还有一些其他页面,url中也有/product
,只是不在路径的开头
正则表达式看起来像什么?/\/product\/(\d+)/
并获得$1
/^\/product\/(\d+)/
查找以/product/开头的路径,然后查找一个或多个数字(在末尾添加i
以支持区分大小写)var res = window.location.pathname.match(/^\/product\/(\d+)/);
if (res.length == 2) {
// use res[1] to get the id.
}
只是,作为替代,在没有Regex的情况下这样做(尽管我承认Regex在这里非常好)
var url=”http://test.example.com//mypage/1/test/test//test";
var newurl=url.replace(“http://”和“).split(“/”);
对于(i=0;i我想建议另一种选择
.match(/\/(\d+)+[\/]?/g)
这将返回id存在的所有匹配项
例如:
var url='1〕http://localhost:4000/#/trees/8/detail/3';
//用斜杠
var id=url.match(/\/(\d+)+[\/]?/g);
控制台日志(ids);
//没有斜线
ids=url.match(//\/(\d++++[\/]?/g).map(id=>id.replace(//\//g');
console.log(ids);
替换函数中的搜索字符串是否接受数组?对于我将来想使用https://
的情况?@PeeHaa我不知道,但您自然可以在那里链接另一个替换函数url.replace(“http://”,“”)。replace(“https://”,“”)…
那不是也会得到:?@Jonathon:对不起,这个坏例子。那不是也会得到:example.com/something/product/1/other-thing吗?:P
.match(/\/(\d+)+[\/]?/g)