JavaScript code explanation for URL parsing query parameters

巴扎黑
Release: 2017-08-08 09:58:51
Original
1373 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:


Copy after login

Calling method:


##

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!