Get URL Search String Parameters with JavaScript - getParameterByName(name,url)

Get URL Search String Parameters with JavaScript - getParameterByName(name,url)




Here is the Code you can use to get the url parameters ....


function getParameterByName(name, 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, ' '));
}

For Example :-
I have URL :- https://mywebsite.com/about?name=John&age=17 and we want to see the value of name .
Here value is John.
So for getting the value run getParameterByName('name') function. to get John as returned value.

However the second parameter is optional but if you want to get search string from a string instead of current url then you can pass the string in second parameter.

i.e. 



var str = https://mywebsite.com/about?name=John&age=17;
var age = getParameterByName('age',str);//Extracting your age from String instead of URL

console.log('Your Age is '+ age);


//Your Function is Here
function getParameterByName(name, 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, ' '));
}


Comments