Javascript and jquery method to get address bar url parameters
- 2020-03-30 02:12:23
- OfStack
Using jquery to get the url and using jquery to get the url parameters is something that we often use
1, jquery to get the url is very simple, the code is as follows
window.location.href;
In fact, it just USES the basic window object of javascript, without any knowledge of jquery
2, jquery to get url parameters is complex, to use regular expressions, so learn how important javascript regular things
So let's first look at how you can get a parameter in a url simply by javascript. Okay
function getUrlParam(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //Construct a regular expression object with the target parameters
var r = window.location.search.substr(1).match(reg); //Matching target parameters
if (r!=null) return unescape(r[2]); return null; //Return parameter value
}
The value of the parameter can be obtained by passing the parameter name in the url through this function, for example, the url is
http://www.xxx.loc/admin/write-post.php? Cid = 79
To get the value of cid, we can write:
getUrlParam('cid');
Knowing how javascript gets url parameters, we can extend a method for jquery to get url parameters through jquery
The code extends a getUrlParam() method for jquery
(function($){
$.getUrlParam
= function(name)
{
var reg
= new RegExp("(^|&)"+
name +"=([^&]*)(&|$)");
var r
= window.location.search.substr(1).match(reg);
if (r!=null) return unescape(r[2]); return null;
}
})(jQuery);
After extending this method for jquery, we can get the value of a parameter in the following way
$.getUrlParam('cid');