js解析url查询参数

xiaoxiao2021-02-28  120

split方法 var path = 'www.u.com/home?id=2&type=0&dtype=-1'; function parseUrl(url){ var result = []; var query = url.split("?")[1]; var queryArr = query.split("&"); queryArr.forEach(function(item){ var obj = {}; var value = item.split("=")[1]; var key = item.split("=")[0]; obj[key] = value; result.push(obj); }); return result; } console.log(parseUrl(path)); //[{id: '2'},{type: '0'},{dtype: '-1'}] 正则 var regex = /[^&=?]+=[^&]*/g; var res = url.match(regex);

//example:

res = "www.u.com/home?id=2&type=0&dtype=-1".match(refex); //["id=2", "type=0", "dtype=-1"]

也可以写一个方法用来取得具体的一个参数值:

var getParamValue = function(url,key){ var regex = new RegExp(key+"=([^&]*)","i"); return url.match(regex)[1]; } getParamValue( "www.u.com/home?id=2&type=0&dtype=-1","id") //2 getParamValue( "www.u.com/home?id=2&type=0&dtype=-1","dtype"); //-1 getParamValue( "www.u.com/home?id=2&type=0&dtype=-1","type") //0
转载请注明原文地址: https://www.6miu.com/read-50182.html

最新回复(0)