Tuesday 20 December 2016

Get url parameter jquery Or How to Get Query String Values In js

Admittedly I'm adding my answer to an over-answered question, but this has the advantages of:


-- Not depending on any outside libraries, including jQuery


-- Not polluting global function namespace, by extending 'String'


-- Not creating any global data and doing unnecessary processing after match found


-- Handling encoding issues, and accepting (assuming) non-encoded parameter name


-- Avoiding explicit for loops


String.prototype.urlParamValue = function() {
var desiredVal = null;
var paramName = this.valueOf();
window.location.search.substring(1).split('&').some(function(currentValue, _, _) {
var nameVal = currentValue.split('=');
if ( decodeURIComponent(nameVal[0]) === paramName ) {
desiredVal = decodeURIComponent(nameVal[1]);
return true;
}
return false;
});
return desiredVal;
};

Then you'd use it as:


var paramVal = "paramName".urlParamValue() // null if no match

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...