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

Abd*_*ziz 95 javascript query-string

我有这样的URL:

http://localhost/PMApp/temp.htm?ProjectID=462
Run Code Online (Sandbox Code Playgroud)

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

到目前为止我所做的是:

var url = window.location.toString();
url.match(?);
Run Code Online (Sandbox Code Playgroud)

我不知道接下来该做什么.

Chr*_*son 213

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

QueryString可用于window.location.search.

也适用于旧版浏览器的解决方案

MDN提供了如何获取QueryString中可用的单个键的获取值的示例(在上面引用的文章中不再可用).像这样的东西:

function getQueryStringValue (key) {  
  return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));  
}  

// Would write the value of the QueryString-variable called name to the console  
console.log(getQueryStringValue("name")); 
Run Code Online (Sandbox Code Playgroud)

在现代浏览器中

在现代浏览器中,您具有searchParamsURL接口的属性,该接口返回URLSearchParams对象.返回的对象有许多方便的方法,包括get-method.所以上面例子的等价物是:

let params = (new URL(document.location)).searchParams;
let name = params.get("name");
Run Code Online (Sandbox Code Playgroud)

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

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

searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true
Run Code Online (Sandbox Code Playgroud)

请注意,此界面仍然限制浏览器支持,因此如果您需要支持旧版浏览器,请坚持使用第一个示例或使用polyfill.


Sta*_*arx 51

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

例:

var url = window.location.search;
url = url.replace("?", ''); // remove the ?
alert(url); //alerts ProjectID=462 is your case
Run Code Online (Sandbox Code Playgroud)

  • 甚至更简单:`let querystring = window.location.search.substring(1);` (12认同)

Dan*_*ker 13

decodeURI(window.location.search)
  .replace('?', '')
  .split('&')
  .map(param => param.split('='))
  .reduce((values, [ key, value ]) => {
    values[ key ] = value
    return values
  }, {})
Run Code Online (Sandbox Code Playgroud)


roy*_*key 7

这将添加一个全局函数来访问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);
    }
}
Run Code Online (Sandbox Code Playgroud)

请享用.


LeO*_* Li 7

如果你碰巧使用了Typescript并且在你的lib中有dom,你可以这样做: 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');
Run Code Online (Sandbox Code Playgroud)


Nur*_*uda 7

您可以简单地使用URLSearchParams().

让我们看看我们有一个带有 url 的页面:

  • https://example.com/?product=1&category=game

在该页面上,您可以使用获取查询字符串window.location.search,然后使用URLSearchParams()类提取它们。

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

console.log(params.get('product')
// 1

console.log(params.get('category')
// game
Run Code Online (Sandbox Code Playgroud)

另一个使用动态 url(不是来自window.location)的示例,您可以使用 URL 对象提取 url。

const url = new URL('https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest')

console.log(url.search)
// ?v=6xJ27BtlM0c&ab_channel=FliteTest
Run Code Online (Sandbox Code Playgroud)

这是一个简单的工作片段:

const urlInput = document.querySelector('input[type=url]')
const keyInput = document.querySelector('input[name=key]')
const button = document.querySelector('button')
const outputDiv = document.querySelector('#output')

button.addEventListener('click', () => {
    const url = new URL(urlInput.value)
    const params = new URLSearchParams(url.search)
    output.innerHTML = params.get(keyInput.value)
})
Run Code Online (Sandbox Code Playgroud)
div {
margin-bottom: 1rem;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <label>URL</label> <br>
  <input type="url" value="https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest">
</div>

<div>
  <label>Params key</label> <br>
  <input type="text" name="key" value="v">
</div>

<div>
  <button>Get Value</button>
</div>

<div id="output"></div>
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用它通过参数名称直接查找值。

const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
Run Code Online (Sandbox Code Playgroud)