如何使用JavaScript获取查询字符串值

5

i have an URL like the followin,

http://test.com/testing/test/12345

12345是id。我想使用查询字符串获取它。如何在JavaScript中获取这个值?


可能是 https://dev59.com/nHNA5IYBdhLWcg3wmfAa?rq=1 的重复问题。 - vidya sagar
5个回答

5

试试这样做

http://test.com/testing/test/12345

var aarr = window.location.href.split('/');
//get last value
var id = aarr[aarr.length -1];

或者只是。
 var id = window.location.href.split('/').pop()

3

使用以下代码:

document.location.href.split('/').pop()

在此页面上运行它将得到:22139563#22139563


2
@drewish(我的电脑有SSD硬盘...):-) - Royi Namir
投票支持你,因为你比我更快地写出了pop()的代码 ;) - drewish

2
请使用以下代码:
var id = location.split('/').pop();

1

我会使用substring,因为我认为它比创建一个数组更轻量级:

var id = window.location.href;
id = id.substring(id.lastIndexOf('/')+1);

1
那是路径的一部分,不是查询字符串...但您可以使用window.location访问页面的URL。
路径可在window.location.pathname中获得,可以使用正斜杠拆分:window.location.pathname.split('/') 然后,您可以获取数组的最后一个项目:window.location.pathname.split('/').pop()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接