Get URL Search String Parameters with JavaScript -
getParameterByName(name,url)
See Demo Here :- https://tutorials.sh20raj.repl.co/getparameterbyname/congrats.html?name=SHRaj&age=16&class=11 or https://tutorials.sh20raj.repl.co/getparameterbyname/
See Sample Codes :- https://replit.com/@SH20RAJ/Tutorials#getparameterbyname/congrats.html
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
Post a Comment