JavaScript获取url参数
声明:以下内容转自网络
方法一
String.prototype.getUrlString = function(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = this.substr(this.indexOf("?") + 1).match(reg); if (r != null) return unescape(r[2]); return null; }; alert(top.window.location.href.getUrlString("r"));
方法二
function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return decodeURIComponent(r[2]); return null; }
方法三
function geturlParam(name) { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars[name]; }
方法四
function urlArgs() { var args = {}; // Start with an empty object var query = location.search.substring(1); // Get query string, minus '?' var pairs = query.split("&"); // Split at ampersands for(var i = 0; i < pairs.length; i++) { // For each fragment var pos = pairs[i].indexOf('='); // Look for "name=value" if (pos == -1) continue; // If not found, skip it var name = pairs[i].substring(0,pos); // Extract the name var value = pairs[i].substring(pos+1); // Extract the value value = decodeURIComponent(value); // Decode the value args[name] = value; // Store as a property } return args; // Return the parsed arguments }
方法五
function getQueryStringArgs(){ //get query string without the initial ? var qs = (location.search.length > 0 ? location.search.substring(1) : ""), //object to hold data args = {}, //get individual items items = qs.length ? qs.split("&") : [], item = null, name = null, value = null, //used in for loop i = 0, len = items.length; //assign each item onto the args object for (i=0; i < len; i++){ item = items[i].split("="); name = decodeURIComponent(item[0]); value = decodeURIComponent(item[1]); if (name.length){ args[name] = value; } } return args; } //assume query string of ?q=javascript&num=10 var args = getQueryStringArgs(); alert(args["q"]); //"javascript" alert(args["num"]); //"10"