javascript中获取标准URL的参数
/** * 获取标准URL的参数 * @_key:字符串,不支持数组参数(多个相同的key) * @_url:字符串,(window).location.href,使用时别误传入非window对象 * @_spliter:字符串,参数间分隔符 * 注意: * 1、如不存在指定键,返回空字符串,方便直接显示,使用时注意判断 * 2、非标准URL勿用 * 3、query(?)与hash(#)中存在键值一样时,以数组返回 */ function getUrlParams(_key, _url, _spliter) { if (typeof(_url) == "object") { var url = _url.location.href; } else { var url = _url ? _url : window.location.href; } if (url.indexOf("?") == -1 && url.indexOf("#") == -1) { return ""; } var spliter = _spliter || "&"; var spliter_1 = "#"; var haveQuery = false; var x_0 = url.indexOf(spliter); var x_1 = url.indexOf(spliter_1); var urlParams; if (x_0 != -1 || x_1 != -1 || url.indexOf("?") != -1) { if(url.indexOf("?") != -1) urlParams = url.split("?")[1]; else if(url.indexOf("#") != -1) urlParams = url.split("#")[1]; else urlParams = url.split(spliter)[1]; if (urlParams.indexOf(spliter) != -1 || urlParams.indexOf(spliter_1) != -1) {//可能出现 url?a=1&b=3#c=2&d=5 url?a=1&b=2 url#a=1&b=2的情况。 var v = []; if(urlParams.indexOf(spliter_1) != -1){ v = urlParams.split(spliter_1); urlParams = []; for(var x = 0; x < v.length; x++){ urlParams = urlParams.concat(v[x].split(spliter)); } }else{ urlParams = urlParams.split(spliter); } } else { urlParams = [urlParams]; } haveQuery = true; } else { urlParams = [url]; } var valueArr = []; for (var i = 0, len = urlParams.length; i < len; i++) { var params = urlParams[i].split("="); if (params[0] == _key) { valueArr.push(params[1]); } } if (valueArr.length > 0) { if (valueArr.length == 1) { return valueArr[0]; } return valueArr; } return ""; } //*****************************获取标准URL的参数 end********************//