用JavaScript按一定格式解析出URL 串中所有的参数

1、先看看location对象

2、其中的search属性就获取当前URL的查询部分(问号?之后的部分)

3、改造location.search

比如当前URL为:https://www.hao123.com/?name=leaf&age=12,获取age的值

location.search.substring(1).split('&')[1].split('=')[1]。
当然可以用循环获取所有想要字段的值

4、不用location.search,封装一个param函数,解析出给你url的参数;

//如定的url:
 'http://www.baidu.com/?user=leaf&age=10&id=123&id=456&city=%E5%8C%97%E4%BA%AC&d&student';

 //解析出:
 //要求:
 // 重复出现的 key 要组装成数组,能被转成数字的就转成数字类型
 // 解析出中文
 // 未指定值的 key 约定值为 true
{
  user: 'anonymous',
  age:10,
  id: [123, 456],    
  city: '北京',        
  student: true,      
}

  

//demo

function parseURL(str){
 	//如果参数不是对象。返回空对象
 	if(typeof str!='string'){
 		return {}
 	}

 	var paramObj = {},//保存最终输出的对象
 	    _str = str.substr(str.indexOf('?')+1);

 	//解析中文
 	paraArr = decodeURI(_str).split("&");

 	var tmp , key, value, newValue;
 	for(var i=0, len=paraArr.length; i<len;i++){
 		tmp = paraArr[i].split("=");
 		key = tmp[0];
 		value = tmp[1]||true;

 		//处理数字'100'=>100
 		if(typeof value === 'string' && isNaN(Number(value)) === false){
 			value = Number(value);
 		}

 		//如果key没有出现过(可能是0 或者false)
 		if(typeof paramObj[key] === "undefined"){
 			paramObj[key] = value;
 		}else{
 			newValue = Array.isArray(paramObj[key]) ? paramObj[key] : [paramObj[key]];
 			newValue.push(value);
 			paramObj[key] = newValue;
 		}

 	}

 	 return paramObj;

 }

//结果

 5、简单小巧的正则的方法

function getQuerystring(name){
	let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     	let arg = window.location.search.substr(1).match(reg);
     	if(arg!=null){
     		return  unescape(r[2]);
     	}else{
     		return null;
     	}
}

  

 

如URL:www.hao123.com/dist/redPacket/inviteShare.html?code=B197FD&from=singlemessage

getQuerystring('code')  //B197FD


 

  

原文地址:https://www.cnblogs.com/leaf930814/p/6868894.html