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

我有这样的网址:

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

我需要做的是获得 ?符号(查询字符串)之后的详细信息-即 ProjectID=462。如何使用 JavaScript 实现这一点?

到目前为止,我所做的是:

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

我不知道下一步该怎么办。

394536 次浏览

看看关于 window.locationMDN 文章

QueryString 在 window.location.search中可用。

如果希望使用更方便的接口,可以使用 URL 接口的 searchParams属性,该属性返回 URLSearchParams对象。返回的对象有许多方便的方法,包括 get 方法。因此,上面例子的等价物是:

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

URLSearchParams接口还可以用于以 querystring 格式解析字符串,并将它们转换为方便的 URLSearchParams 对象。

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


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

URLSearchParams 接口现在在浏览器中被广泛采用(根据 我能用吗,超过95%) ,但是如果您确实需要支持遗留浏览器,那么您可以使用 填料

可以使用 window.location对象的 search属性获取 URL 的查询部分。注意,它包括问号(?)以防影响您解析它的方式。

使用 window.location.search获取 ? 包括 ?之后的所有内容

例如:

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

这将添加一个全局函数以作为映射访问 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);
}
}

好好享受吧。

对于从? id = 拆分字符串,可以使用此函数

 function myfunction(myvar){
var urls = myvar;
var myurls = urls.split("?id=");
var mylasturls = myurls[1];
var mynexturls = mylasturls.split("&");
var url = mynexturls[0];
alert(url)
}
myfunction(window.top.location.href);
myfunction("http://www.myname.com/index.html?id=dance&emp;cid=in_social_facebook-hhp-food-moonlight-influencer_s7_20160623");

这是 小提琴

您应该查看一下 URL API,其中包含帮助器方法,以便在 URLSearchParams: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams中实现这一点

目前并非所有的现代浏览器都支持这一点,所以不要忘记填充它(使用 https://qa.polyfill.io/可以填充 Polyfill)。

  var queryObj = {};
if(url.split("?").length>0){
var queryString = url.split("?")[1];
}

现在在 queryString 中有了查询部分

第一个替换将删除所有的空白,第二个替换所有的’&’部分与“ ,最后第三个替换将放置“ :”代替’=’符号。

queryObj = JSON.parse('{"' + queryString.replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')

假设您有一个像 Abc = 123 & efg = 456这样的查询。现在,在解析之前,您的查询将被转换为类似于{“ abc”: “123”,“ efg”: “456”}的内容。现在,当您解析它时,它将在 json 对象中给出您的查询。

  window.location.href.slice(window.location.href.indexOf('?') + 1);

将其转换为数组,然后分割为’?’

var url= 'http://localhost/PMApp/temp.htm?ProjectID=462';


url.split('?')[1];     //ProjectID=462
decodeURI(window.location.search)
.replace('?', '')
.split('&')
.map(param => param.split('='))
.reduce((values, [ key, value ]) => {
values[ key ] = value
return values
}, {})

试试这个

/**
* Get the value of a querystring
* @param  {String} field The field to get the value of
* @param  {String} url   The URL to get the value from (optional)
* @return {String}       The field value
*/
var getQueryString = function ( field, url ) {
var href = url ? url : window.location.href;
var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
var string = reg.exec(href);
return string ? string[1] : null;
};

假设你的 URL 是 http://example.com&this=chicken&that=sandwich,你想得到 this,that,and another 的值。

var thisOne = getQueryString('this'); // returns 'chicken'
var thatOne = getQueryString('that'); // returns 'sandwich'
var anotherOne = getQueryString('another'); // returns null

如果希望使用窗口中的 URL 以外的 URL,可以将其中一个作为第二个参数传入。

var yetAnotherOne = getQueryString('example', 'http://another-example.com&example=something'); // returns 'something'

参考文献

如果你碰巧使用 打印稿,并且在 tsconfig.jsonLib中有 Dom,你可以做:

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');
q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;

您可以通过 params name 使用它直接查找值。

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

我认为依赖浏览器比任何巧妙的正则表达式都要安全得多:

const parseUrl = function(url) {
const a = document.createElement('a')
a.href = url
return {
protocol: a.protocol ? a.protocol : null,
hostname: a.hostname ? a.hostname : null,
port: a.port ? a.port : null,
path: a.pathname ? a.pathname : null,
query: a.search ? a.search : null,
hash: a.hash ? a.hash : null,
host: a.host ? a.host : null
}
}


console.log( parseUrl(window.location.href) ) //stacksnippet
//to obtain a query
console.log( parseUrl( 'https://example.com?qwery=this').query )

这将返回查询参数作为关联数组

var queryParams =[];
var query= document.location.search.replace("?",'').split("&");
for(var i =0; i< query.length; i++)
{
if(query[i]){
var temp = query[i].split("=");
queryParams[temp[0]] = temp[1]
}
}

您可以简单地使用 URLSearchParams()

让我们看看我们有一个网页的网址:

  • 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

另一个使用动态 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

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

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)
})
div {
margin-bottom: 1rem;
}
<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>

8年后,为了一句俏皮话

  const search = Object.fromEntries(new URLSearchParams(location.search));

缺点是,它不能与 IE11一起工作

来解释

  1. URLSearchParams 接口定义使用 URL 的查询字符串的实用工具方法(From,https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
  2. FROM Entry ()方法将一个键值对列表转换为一个对象
// For https://caniuse.com/?search=fromEntries
> Object.fromEntries(new URLSearchParams(location.search))
> {search: "fromEntries"}

对于 React 本机、 React 和 For Node 项目,下面一个正在工作

yarn add  query-string


import queryString from 'query-string';


const parsed = queryString.parseUrl("https://pokeapi.co/api/v2/pokemon?offset=10&limit=10");


console.log(parsed.offset) will display 10