ここには多くの良い解決策がありますが、私は自分自身を投稿することにしました。これは、window.location.search または提供された検索文字列値のいずれかからの形式でクエリ文字列を解析する、私が一緒に投げた簡単な小さな関数です。
ID 値のペアのハッシュを返すため、次の形式で参照できます。
var values = getQueryParams();
values['id']
values['blah']
コードは次のとおりです。
/*
This function assumes that the query string provided will
contain a ? character before the query string itself.
It will not work if the ? is not present.
In addition, sites which don't use ? to delimit the start of the query string
(ie. Google) won't work properly with this script.
*/
function getQueryParams( val ) {
//Use the window.location.search if we don't have a val.
var query = val || window.location.search;
query = query.split('?')[1]
var pairs = query.split('&');
var retval = {};
var check = [];
for( var i = 0; i < pairs.length; i++ ) {
check = pairs[i].split('=');
retval[decodeURIComponent(check[0])] = decodeURIComponent(check[1]);
}
return retval;
}
文字列を解析せずに URL からクエリ文字列の値を取得するには、次のようにします。
window.location.search.substr(1)
? の前にページの名前が必要な場合 少し文字列の解析を行う必要があります。
var path = window.location.pathname.replace(/^.*\/(.*)$/,'$1');
var query = path + window.location.search;
//If your URL is http://www.myserver.com/some/long/path/big_long%20file.php?some=file&equals=me
//you will get: big_long%20file.php?some=file&equals=me
お役に立てれば!乾杯。