Home > Web Front-end > JS Tutorial > body text

JavaScript code explanation for URL parsing query parameters

巴扎黑
Release: 2017-08-08 09:58:51
Original
1463 people have browsed it

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'}]
Copy after login

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; 
}
Copy after login

Calling method:


alert(GetQueryString("参数名1"));alert(GetQueryString("参数名2")); 
alert(GetQueryString("参数名3"));
Copy after login

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>
Copy after login

Calling method:


##

<Script language="javascript"> 
var Request = new Object(); 
Request = GetRequest(); 
var 参数1,参数2,参数3,参数N; 
参数1 = Request[&#39;参数1&#39;]; 
参数2 = Request[&#39;参数2&#39;]; 
参数3 = Request[&#39;参数3&#39;]; 
参数N = Request[&#39;参数N&#39;]; 
</Script>
Copy after login

The above is the detailed content of JavaScript code explanation for URL parsing query parameters. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template