This article introduces you to the method of js parsing url query parameters through simple code, and then introduces to you two ways of js to obtain url parameter values at the bottom of the article. It is very good and has reference value. Friends who need it can refer to it. Okay
No more nonsense, I will post the code directly for everyone. The specific code is as follows:
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("=")[0]; var key = item.split("=")[1]; obj[key] = value; result.push(obj); }); return result; } console.log(parseUrl(path)); //[{id: '2'},{type: '0'},{dtype: '-1'}]
Okay , let’s take a look at the two ways to get the url parameter value in js
Method 1: Regular analysis method
The code is as follows:
function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; }
Calling method:
alert(GetQueryString("参数名1"));alert(GetQueryString("参数名2")); alert(GetQueryString("参数名3"));
Method 2
The code is as follows:
<Script language="javascript"> function GetRequest() { var url = location.search; //获取url中"?"符后的字串 var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for(var i = 0; i < strs.length; i ++) { theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]); } } return theRequest; } </Script>
Calling method:
<Script language="javascript"> var Request = new Object(); Request = GetRequest(); var 参数1,参数2,参数3,参数N; 参数1 = Request['参数1']; 参数2 = Request['参数2']; 参数3 = Request['参数3']; 参数N = Request['参数N']; </Script>
Okay, that’s it.
The above is the detailed content of Detailed example of how JavaScript parses url query parameters. For more information, please follow other related articles on the PHP Chinese website!