如何從JavaScript中的查詢字符串中的瀏覽器URL中提取獲取參數。如何從JavaScript中的查詢字符串URL中提取獲取參數
這是網址。 http://localhost/test/test.html?q=mySearchString#do/users/view
我知道可以使用window.location的
如何從JavaScript中的查詢字符串中的瀏覽器URL中提取獲取參數。如何從JavaScript中的查詢字符串URL中提取獲取參數
這是網址。 http://localhost/test/test.html?q=mySearchString#do/users/view
我知道可以使用window.location的
返回整個URL讓我們假設您的網址是: http://localhost/test/test.html?q=mySearchString#do/users/view
以下功能將提取位置,路徑,散列的queryString,得到的參數和來自此網址的細分。
function suPlayWithLocation(doWhat, arg) {
//doWhat options: location, path, hash, queryString, get and segment
//Pass arg as 0 (zero) for location, path, hash and queryString
//Pass arg as the get parameter name for queryString
//Pass arg as the segment number for segment
//Get location
if (doWhat == 'location') {
if (window.location) {
return window.location;
}
}
//Get path
if (doWhat == 'path') {
if (window.location.pathname) {
return window.location.pathname;
}
}
//Get hasg
if (doWhat == 'hash') {
if (window.location.hash) {
return window.location.hash.substr(1);
}
}
//Get query string
if (doWhat == 'queryString') {
if (window.location.search) {
return window.location.search.substr(1);
}
}
//Get the value of get parameter
if (doWhat == 'get') {
if (window.location.search) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === arg)
result = decodeURIComponent(tmp[1]);
}
return result;
}
}
//Get segment value
if (doWhat == 'segment') {
if (window.location.hash) {
arg = arg - 1;
segment = window.location.hash.substr(1).split('/');
return segment[arg];
}
}
}
alert(suPlayWithLocation('location',0)); //返回http://localhost/test/test.html?q=mySearchString#do/users/view
alert(suPlayWithLocation('path',0)); //返回http://localhost/test/test.html
alert(suPlayWithLocation('hash',0)); //返回do/users/view
alert(suPlayWithLocation('queryString',0)); //返回q = mySearchString
alert(suPlayWithLocation('get','q')); //返回mySearchString
alert(suPlayWithLocation('segment','2')); //返回用戶
的今天最簡單的將是一個地圖查詢:
var query=new Map(location.href.split("#")[0].split("?")[1].split("&").map(el=>el.split("=")));
所以,你可以這樣做:
console.log(query.get("q"))//mySearchString
這只是實現了查詢參數(您的問題關於)。
爲什麼你需要這第一個參數?你不能像* parser.get(「q」)*一樣實現它嗎? –