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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7722683/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:04:24  来源:igfitidea点击:

How to get all Query string values using JavaScript

javascriptquery-string

提问by amit

I want to get the values of all parameters of query string from URL.

我想从 URL 获取查询字符串的所有参数的值。

Example: www.xyz.com?author=bloggingdeveloper&a1=hello

例子: www.xyz.com?author=bloggingdeveloper&a1=hello

I want to get values of authorand a1parameters using JavaScript.

我想使用 JavaScript获取authora1参数的值。

回答by Ayesha Mundu

The simplest way to do so is:-

最简单的方法是:-

const search = /*your search query ex:-?author=bloggingdeveloper&a1=hello*/
const params = new URLSearchParams(search);
let paramObj = {};
for(var value of params.keys()) {
     paramObj[value] = params.get(value);
 }

if you console paramObj you will get :-

如果你控制台 paramObj 你会得到:-

{
author: bloggingdeveloper,
a1: hello
}

simple!!

简单的!!

refer:- https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/keys

参考:- https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/keys

回答by TimT

function getUrlVars()
{
    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 author = getUrlVars()["author"];
var a1 = getUrlVars()["a1"];

回答by TheGremlyn

I found this question and started using the answer suggested by TimT, but found that I would run into situations where my URL did not always have a query string. TimT's function would simply return the URL, but I found it better to either return an array of vars from the query string OR simply return false for easy checking.

我发现了这个问题并开始使用 TimT 建议的答案,但发现我会遇到我的 URL 并不总是有查询字符串的情况。TimT 的函数会简单地返回 URL,但我发现最好是从查询字符串中返回一个变量数组,或者简单地返回 false 以便于检查。

I further changed it to use window.location.search, as the query string is already provided to us without having to separate it out.

我进一步将其更改为使用 window.location.search,因为查询字符串已经提供给我们,而无需将其分开。

function getUrlVars() {
    var vars = [], hash;
    var query_string = window.location.search;

    if (query_string) {
        var hashes = query_string.slice(1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars[hash[0]] = hash[1];
        }

        return vars;
    } else {
        return false;
    }
}

回答by Dan Zuzevich

If you are dealing with good developers, I don't think this is overly complicated to reason about. Converts the iterator from param.keys() to an array so you can use reduce.

如果您正在与优秀的开发人员打交道,我认为这并不太复杂。将迭代器从 param.keys() 转换为数组,以便您可以使用 reduce。

const params = new URLSearchParams(window.location.search);

const paramsObj = Array.from(params.keys()).reduce(
  (acc, val) => ({ ...acc, [val]: params.get(val) }),
  {}
);

回答by NilColor

You can use something like this:

你可以使用这样的东西:

function parseQuerystring(){
    var foo = window.location.href.split('?')[1].split('#')[0].split('&');
    var dict = {};
    var elem = [];
    for (var i = foo.length - 1; i >= 0; i--) {
        elem = foo[i].split('=');
        dict[elem[0]] = elem[1];
    };
    return dict;
};

Function return JS-object from your querystring.

函数从您的查询字符串返回 JS 对象。

//www.xyz.com?author=bloggingdeveloper&a1=hello
>parseQuerystring()
{
  author: bloggingdeveloper,
  a1: hello
}

回答by Shlomi Komemi

try this:

试试这个:

function urlParameter() {
    var url = window.location.href,
    retObject = {},
    parameters;

    if (url.indexOf('?') === -1) {
        return null;
    }

    url = url.split('?')[1];

    parameters = url.split('&');

    for (var i = 0; i < parameters.length; i++) {
        retObject[parameters[i].split('=')[0]] = parameters[i].split('=')[1];
    }

    return retObject;
}

output json object:

输出json对象:

{
     author : 'bloggingdeveloper',
     a1 : 'hello'
}

get a specific value:

获取特定值:

var author = urlParameter().author;
alert(author);

回答by Manse

This stores the URL Parameters so is efficient (granted it uses a global :-( ):

这存储了 URL 参数,因此效率很高(授予它使用全局 :-( ):

var urlParams = {};
(function () {
    var e,
    a = /\+/g,  // Regex for replacing addition symbol with a space
    r = /([^&=]+)=?([^&]*)/g,
    d = function (s) {
        return decodeURIComponent(s.replace(a, " "));
    },
    q = window.location.search.substring(1);

    while (e = r.exec(q))
        urlParams[d(e[1])] = d(e[2]);
})();

回答by Merianos Nikos

Use that

使用那个

var get_vars = window.location.search;
var patt1 = /author\=(.+)\&/;
alert(get_vars.match(patt1)[1]);

The above code acts like that

上面的代码就像这样

loading into get_vars variable only the query string from the domain
then assinging a regular expression pattern into patt1 that can match the author variable and it;s value
finaly alerting the matched username

仅将域中的查询字符串加载到 get_vars 变量中,
然后将正则表达式模式分配到 patt1 中,该模式可以匹配作者变量及其值,最终
提醒匹配的用户名

回答by balaphp

          var search = function() {
          var p = window.location.search.substr(1).split(/\&/), l = p.length, kv, r = {};
          while (l--) {
             kv = p[l].split(/\=/);
             r[kv[0]] = kv[1] || true; //if no =value just set it as true
          }
             return r;
          }();

回答by Guilherme Calabria

Set an identification on the URL like url.com?id=9, then send this as a parameter to call the function and use URLSearchParams.

在 URL 上设置一个标识url.com?id=9,然后将其作为参数发送以调用函数并使用URLSearchParams