In this article, we will learn how to get URL parameters or QueryString and their values using Jquery.
Every server-side language provides a direct method to get URL parameter or QueryString values, but in client-side it is not easy to get URL parameter or QueryString values as in server-side languages.
Here is the code, to get the URL parameter values or QueryString values.
Here we are using the URL with QueryString is given Below:
https://localhost:44399/Home/GetURLbyJquery?id=1234&name=Tutorials%20Rack
Use this method to get the URL Parameter
function getUrlParameter(ParamName) {
name = ParamName.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(window.location.href);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
console.log(getUrlParameter('id'));
console.log(getUrlParameter('name'));
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('name')); // true
console.log(urlParams.get('name')); // " Tutorials Rack"
console.log(urlParams.getAll('name')); // ["Tutorials Rack"]
console.log(urlParams.toString()); // "?id=1234&name= Tutorials Rack"
Check For browser support - Click Here
URLSearchParams also provides familiar Object methods like keys()
, values()
, and entries()
:
var keys = urlParams.keys();
for (key of keys) {
console.log(key);
}
// The above code returns
// id
// name
var entries = urlParams.entries();
for(pair of entries) {
console.log(pair[0], pair[1]);
}
//This returns the pair of key and value pairs
//id 1234
//name Tutorials rack
For More Information on URLSearchParams API – Click Here
Click Here For Jquery Plugin Link
download the plugin from the above-given link and use then after below-given code is working.
//https://localhost:44399/Home/GetURLbyJquery?id=1234&name=Tutorials%20Rack#madeby=sourabh%20chauhan
$(function () {
console.log(url()); // https://localhost:44399/Home/GetURLbyJquery?id=1234&name=Tutorials%20Rack#madeby=sourabh%20chauhan
console.log(url('query')); // id=1234&name=Tutorials%20Rack
console.log(url('?')); // {id: '1234', name: 'Tutorials Rack'}
console.log(url('?id')); // 1234
console.log(url('?name')); // Tutorials Rack
//If You want to get the Value after #
console.log(url('hash')); // madeby=sourabh%20chauhan
console.log(url('#')); // {madeby: "sourabh chauhan"}
console.log(url('#madeby')); // sourabh chauhan
console.log(url('#poo')); // undefined
});
For More info about the plugin - Click Here
I hope this article will help you to understand How to get URL parameter using jquery Or How to get QueryString values using jquery.
Share your valuable feedback and help us to improve. If you find anything incorrect, or you want to share more information about the topic discussed above. please post your comment at the bottom of this article. Thank you!
Comments