Javascript 如何通过javascript获取查询字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2907482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the query string by javascript?
提问by Jayesh
How to extract the query string from the URL in javascript?
如何从javascript中的URL中提取查询字符串?
Thank you!
谢谢!
回答by Josh Stodola
You can easily build a dictionary style collection...
您可以轻松构建字典样式集合...
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
}
And use it like this...
并像这样使用它......
var qs = getQueryStrings();
var myParam = qs["myParam"];
回答by Syntactic
If you're referring to the URL in the address bar, then
如果您指的是地址栏中的 URL,则
window.location.search
will give you just the query string part. Note that this includes the question mark at the beginning.
只会给你查询字符串部分。请注意,这包括开头的问号。
If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:
如果您指的是存储在(例如)字符串中的任何随机 URL,您可以通过执行以下操作获取从第一个问号索引开始的子字符串来获取查询字符串:
url.substring(url.indexOf("?"))
That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.
这假设 URL 片段部分中的任何问号都已正确编码。如果末尾有目标(即,# 后跟 DOM 元素的 id),它也会包含该目标。
回答by user2788596
You need to simple use following function.
您需要简单使用以下功能。
function GetQueryStringByParameter(name) {
name = name.replace(/[\[]/, "\[").replace(/[\]]/, "\]");
var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
--- How to Use ---
- - 如何使用 - -
var QueryString= GetQueryStringByParameter('QueryString');
回答by B.B
Here's the method I use...
这是我使用的方法...
function Querystring() {
var q = window.location.search.substr(1), qs = {};
if (q.length) {
var keys = q.split("&"), k, kv, key, val, v;
for (k = keys.length; k--; ) {
kv = keys[k].split("=");
key = kv[0];
val = decodeURIComponent(kv[1]);
if (qs[key] === undefined) {
qs[key] = val;
} else {
v = qs[key];
if (v.constructor != Array) {
qs[key] = [];
qs[key].push(v);
}
qs[key].push(val);
}
}
}
return qs;
}
It returns an object of strings and arrays and seems to work quite well. (Strings for single keys, arrays for the same key with multiple values.)
它返回一个字符串和数组的对象,似乎工作得很好。(单个键的字符串,具有多个值的同一个键的数组。)
回答by Andy
Very Straightforward!
很直接!
function parseQueryString(){
var assoc = {};
var keyValues = location.search.slice(1).split('&');
var decode = function(s){
return decodeURIComponent(s.replace(/\+/g, ' '));
};
for (var i = 0; i < keyValues.length; ++i) {
var key = keyValues[i].split('=');
if (1 < key.length) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
}
回答by Abhimanyu Garg
Works for me-
对我有用-
function querySt(Key) {
var url = window.location.href;
KeysValues = url.split(/[\?&]+/);
for (i = 0; i < KeysValues.length; i++) {
KeyValue= KeysValues[i].split("=");
if (KeyValue[0] == Key) {
return KeyValue[1];
}
}
}
function GetQString(Key) {
if (querySt(Key)) {
var value = querySt(Key);
return value;
}
}
回答by nils
There is a new API called URLSearchParamsin browsers which allow you to extract and change the values of the query string.
浏览器中有一个新的 APIURLSearchParams,它允许您提取和更改查询字符串的值。
Currently, it seems to be supported in Firefox 44+, Chrome 49+ and Opera 36+.
目前,它似乎在 Firefox 44+、Chrome 49+ 和 Opera 36+ 中受支持。
Initialize/Input
初始化/输入
To get started, create a new URLSearchParams object. For current implementations, you need to remove the "?" at the beginning of the query string, using slice(1)on the querystring, as Jake Archibald suggests:
首先,创建一个新的 URLSearchParams 对象。对于当前的实现,您需要删除“?” 在查询字符串的开头,在查询字符串上使用slice(1),正如 Jake Archibald 建议的那样:
var params = new URLSearchParams(window.location.search.slice(1)); // myParam=12
In later implementations, you should be able to use it without slice:
在以后的实现中,您应该可以在不使用切片的情况下使用它:
var params = new URLSearchParams(window.location.search); // myParam=12
Get
得到
You can get params from it via the .getmethod:
您可以通过以下.get方法从中获取参数:
params.get('myParam'); // 12
Set
放
Params can be changed using .set:
可以使用.set以下方法更改参数:
params.set('myParam', 'newValue');
Output
输出
And if the current querystring is needed again, the .toStringmethod provides it:
如果再次需要当前查询字符串,该.toString方法会提供它:
params.toString(); // myParam=newValue
There are a host of other methods in this API.
Polyfill
填充物
As browser support is still pretty thin, there is a small polyfill by Andrea Giammarchi (<3kB).
由于浏览器支持仍然非常薄弱,因此Andrea Giammarchi (<3kB) 提供了一个小的 polyfill。
回答by praveen kedar
// Assuming "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
回答by Gagan Gami
You can use this Javascript:
您可以使用此Javascript:
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
OR
或者
You can also use the plugin jQuery-URL-Parserallows to retrieve all parts of URL, including anchor, host, etc.
您还可以使用插件jQuery-URL-Parser允许检索 URL 的所有部分,包括锚点、主机等。
Usage is very simple and cool:
用法很简单很酷:
$.url().param("itemID")
via James&Alfa
通过詹姆斯和阿尔法
回答by Amay Kulkarni
I have use this method
我用过这个方法
function getString()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var buisnessArea = getString();

