In this article am going to explain how to read query string value using JavaScript.
Use the following function to read query string value from url. You just need to pass the parameter name to this function.
Method 1:
Method 2 :
You can also use the following javascript function to read querystring value.
For example assume url as http://mysite.com?myParam1=test1&myParam2=test2
Now to read the query string value from above url use the following javascript code.
In this way we can read query string value from url in JavaScript
Use the following function to read query string value from url. You just need to pass the parameter name to this function.
Method 1:
var getQueryString = function ( field) {
var href = window.location.href;
var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
var string = reg.exec(href);
return string ? string[1] : null;
};
Method 2 :
You can also use the following javascript function to read querystring value.
function getQueryString(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
For example assume url as http://mysite.com?myParam1=test1&myParam2=test2
Now to read the query string value from above url use the following javascript code.
var myParam1 = getQueryString('myParam1'); // returns 'test1'
var myParam2 = getQueryString('myParam2'); // returns 'test2'
var testParam = getQueryString('something'); // returns null
Note: If a parameter is present several times (?param=test1¶m=test2), you will get the first value
In this way we can read query string value from url in JavaScript
For more posts on javascript visit: JavaScript
No comments:
Post a Comment