如何在JavaScript中获取查询字符串值? [英] How can I get query string values in JavaScript?

查看:256
本文介绍了如何在JavaScript中获取查询字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种无插件的方法可以通过jQuery检索查询字符串值(或者没有)?

Is there a plugin-less way of retrieving query string values via jQuery (or without)?

如果是这样,怎么样?如果没有,是否有插件可以这样做?

If so, how? If not, is there a plugin which can do so?

推荐答案

更新:2018年9月

您可以使用简单且具有良好的浏览器支持

You can use URLSearchParams which is simple and has good browser support.

const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');

Orignal

你不需要为此目的使用jQuery。您只能使用一些纯JavaScript:

You don't need jQuery for that purpose. You can use just some pure JavaScript:

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

用法:

// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)



注意:如果参数存在多个时间(?foo = lorem& foo = ipsum ),您将获得第一个值( lorem )。没有关于此的标准和用法不同,请参阅此问题:重复HTTP GET查询键的权威位置

注意:该函数区分大小写。如果您不喜欢不区分大小写的参数名称,请将i修饰符添加到RegExp


Note: If a parameter is present several times (?foo=lorem&foo=ipsum), you will get the first value (lorem). There is no standard about this and usages vary, see for example this question: Authoritative position of duplicate HTTP GET query keys.
NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, add 'i' modifier to RegExp

这是基于新 URLSearchParams specs 以更简洁的方式实现相同的结果。请参阅标题为 URLSearchParams 的回答下面。

This is an update based on the new URLSearchParams specs to achieve the same result more succinctly. See answer titled "URLSearchParams" below.

这篇关于如何在JavaScript中获取查询字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆