How to get the URL Parameter by name in javascript?

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