如何使用 JavaScript 从当前 URL 获取查询字符串?

IT技术 javascript query-string
2021-02-01 09:30:58

我有这样的网址:

http://localhost/PMApp/temp.htm?ProjectID=462

我需要做的是获取?符号(查询字符串)之后的详细信息- 即ProjectID=462. 我怎样才能使用 JavaScript 获得它?

到目前为止我所做的是:

var url = window.location.toString();
url.match(?);

我不知道接下来要做什么。

6个回答

看一看的MDN文章有关window.location

QueryString 在window.location.search.

如果您想要一个更方便的界面来使用,您可以使用searchParamsURL 界面属性,它返回一个URLSearchParams对象。返回的对象有许多方便的方法,包括 get 方法。所以上面例子的等价物是:

let params = (new URL(document.location)).searchParams;
let name = params.get("name");

URLSearchParams接口也可以用于在查询字符串格式解析字符串,并把它们变成一个方便URLSearchParams对象。

let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);

searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true

URLSearchParams 接口现在在浏览器中被广泛采用(根据Can I Use 95%+ ),但如果你确实需要支持旧浏览器,你可以使用polyfill

@Pratyush 是的,我在答案中提到了这一点,并参考了更流行且更新频率更高的url-search-params-polyfill包。
2021-03-19 09:30:58
const params = (new URL(url)).searchParams; 为我工作。
2021-03-20 09:30:58
请注意:始终使用encodeURIComponent/decodeURIComponent代替escape/unescape
2021-03-22 09:30:58
旧浏览器 (IE) 可以为 URLSearchParams使用polyfill
2021-04-01 09:30:58
getQueryStringValue旧版浏览器的第一个函数不适用于 ?foo=bar&foo1=bar1 如果我们尝试获取 的值foo,它会返回empty string
2021-04-02 09:30:58

使用window.location.search后得到的一切? ,包括?

例子:

var url = window.location.search;
url = url.replace("?", ''); // remove the ?
alert(url); //alerts ProjectID=462 is your case
或者更简单: let querystring = window.location.search.substring(1);
2021-04-02 09:30:58
decodeURI(window.location.search)
  .replace('?', '')
  .split('&')
  .map(param => param.split('='))
  .reduce((values, [ key, value ]) => {
    values[ key ] = value
    return values
  }, {})
好办法。谢谢。一点点修复它:替换检查整个(!)字符串。我们需要删除第一个字符。删除不必要的循环。结果:window.location.search window.location.search.substr(1) .split("&") .reduce((acc, param) => { const [key, value] = param.split("=") ; return { ...acc, [key]: value }; }, {})
2021-04-08 09:30:58

如果你碰巧使用了Typescript并且在你的libdom,你可以这样做: tsconfig.json

const url: URL = new URL(window.location.href);
const params: URLSearchParams = url.searchParams;
// get target key/value from URLSearchParams object
const yourParamValue: string = params.get('yourParamKey');

// To append, you can also leverage api to avoid the `?` check 
params.append('newKey', 'newValue');

这将添加一个全局函数来访问 queryString 变量作为映射。

// -------------------------------------------------------------------------------------
// Add function for 'window.location.query( [queryString] )' which returns an object
// of querystring keys and their values. An optional string parameter can be used as
// an alternative to 'window.location.search'.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query.makeString( object, [addQuestionMark] )'
// which returns a queryString from an object. An optional boolean parameter can be
// used to toggle a leading question mark.
// -------------------------------------------------------------------------------------
if (!window.location.query) {
    window.location.query = function (source) {
        var map = {};
        source = source || this.search;

        if ("" != source) {
            var groups = source, i;

            if (groups.indexOf("?") == 0) {
                groups = groups.substr(1);
            }

            groups = groups.split("&");

            for (i in groups) {
                source = groups[i].split("=",
                    // For: xxx=, Prevents: [xxx, ""], Forces: [xxx]
                    (groups[i].slice(-1) !== "=") + 1
                );

                // Key
                i = decodeURIComponent(source[0]);

                // Value
                source = source[1];
                source = typeof source === "undefined"
                    ? source
                    : decodeURIComponent(source);

                // Save Duplicate Key
                if (i in map) {
                    if (Object.prototype.toString.call(map[i]) !== "[object Array]") {
                        map[i] = [map[i]];
                    }

                    map[i].push(source);
                }

                // Save New Key
                else {
                    map[i] = source;
                }
            }
        }

        return map;
    }

    window.location.query.makeString = function (source, addQuestionMark) {
        var str = "", i, ii, key;

        if (typeof source == "boolean") {
            addQuestionMark = source;
            source = undefined;
        }

        if (source == undefined) {
            str = window.location.search;
        }
        else {
            for (i in source) {
                key = "&" + encodeURIComponent(i);

                if (Object.prototype.toString.call(source[i]) !== "[object Array]") {
                    str += key + addUndefindedValue(source[i]);
                }
                else {
                    for (ii = 0; ii < source[i].length; ii++) {
                        str += key + addUndefindedValue(source[i][ii]);
                    }
                }
            }
        }

        return (addQuestionMark === false ? "" : "?") + str.substr(1);
    }

    function addUndefindedValue(source) {
        return typeof source === "undefined"
            ? ""
            : "=" + encodeURIComponent(source);
    }
}

享受。