欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS如何獲取URL中的Query參數(shù)

 更新時間:2023年01月17日 09:18:54   作者:loki951753  
這篇文章主要介紹了JS如何獲取URL中的Query參數(shù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

JS獲取URL的Query參數(shù)

需求描述

獲取 URL 中的 Query 參數(shù),例如:

https://www.example.com/test.html?a=param1&b=param2

代碼片段

實現(xiàn)一

使用URLSearchParams對象,兼容性見Can I use

const urlString = 'https://www.example.com/test.html?a=param1&b=param2';
const urlObj = new URL(urlString);
const [a, b] = urlObj.searchParams.values();

實現(xiàn)二

function parseSearchParams(searchParamsString){
    return searchParamsString.split('&').reduce((searchParams, curKV)=>{
        const [k, v] = curKV.split('=').map(decodeURIComponent);
        searchParams[k] = v;

        return searchParams;
    }, {});
}

JS獲取URL上的指定參數(shù)

function getAllUrlParams(url) {

	// get query string from url (optional) or window
	var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

	// we'll store the parameters here
	var obj = {};

	// if query string exists
	if (queryString) {

		// stuff after # is not part of query string, so get rid of it
		queryString = queryString.split('#')[0];

		// split our query string into its component parts
		var arr = queryString.split('&');
		for (var i = 0; i < arr.length; i++) {
			// separate the keys and the values
			var a = arr[i].split('=');
			// in case params look like: list[]=thing1&list[]=thing2
			var paramNum = undefined;
			var paramName = a[0].replace(/\[\d*\]/, function (v) {
				paramNum = v.slice(1, -1);
				return '';
			});
			// set parameter value (use 'true' if empty)
			var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];
			// if parameter name already exists
			if (obj[paramName]) {
				// convert value to array (if still string)
				if (typeof obj[paramName] === 'string') {
					obj[paramName] = [obj[paramName]];
				}
				// if no array index number specified...
				if (typeof paramNum === 'undefined') {
					// put the value on the end of the array
					obj[paramName].push(paramValue);
				}
				// if array index number specified...
				else {
					// put the value at that index number
					obj[paramName][paramNum] = paramValue;
				}
			}
			// if param name doesn't exist yet, set it
			else {
				obj[paramName] = paramValue;
			}
		}
	}
	return obj;
};
var x = getAllUrlParams('http://127.0.0.1:5000/app/index.html?code=KXMvRUkC92WaJ6n3vELMU3iK2128879&state=').code;
console.log(x);

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論