In this tutorial we are going to read how can get the URL parameter by name in JavaScript, we are creating the common function for this problem. place the below code in your script file.
function getParameterByName(name, url){
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
Here is some instruction to use the getParameterByName
function.
We are getting the page
parameter from https://tutorialwala.com/?page=home
Code:-
var pageurl = 'https://tutorialwala.com/?page=home';
console.log(getParameterByName('page', pageurl))
Output:-
home
Hello Friends, I’m Mohit Sharma funder of tutrialwala.com, Full Stack Web Developer. Expertise in WordPress, PHP, Laravel, Angular, and Frontend Development. In this publication, I share everything I know about PHP frameworks and Javascript frameworks, packages, and tools.
Have a project in mind? Get in touch