In this post, will explain a problem which we often struggle with. How do we get query parameter values from a URL in Javascript?
There isn’t a simple straight forward request object which could help you. However, there are many ways (custom solutions) which you could try. Here is one of the custom solution to get the value of the parameter
Sample Code
// To get array of parameters
function getAllParameters(url) {
var params = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
params[key] = value;
});
return params;
};
//Get the value of the parameter
function getParamValue(param, url){
var paramValue = '';
if(url.indexOf(param) > -1){
paramValue = getAllParameters(url)[param];
}
return paramValue;
}
#INPUT
var sampleURL = 'https://www.example.com?productCode=938939&productName=fcybers';
console.log(getParamValue('productCode' , sampleURL))
console.log(getParamValue('productName' , sampleURL))
#OUTPUT
938939
fcybers
No comments:
Post a Comment
If you have any doubts or questions, please let us know.