Can URLSearchParams somehow find param and not be case senstive?
For example in query I have ?someParam=paramValue, so when I have
URLSearchParams.get("someparam") will it find paramValue?
URLSearchParams keys are case sensitive. I don't see any suggestion in the MDN docs or specification to suggest a flag controlling that behavior or an alternative method, etc.
It's quite straightfoward to convert all the names to lower case in a new URLSearchParams object, though:
const newParams = new URLSearchParams();
for (const [name, value] of params) {
newParams.append(name.toLowerCase(), value);
}
Or if you want to condense it some:
const newParams = new URLSearchParams(
Array.from(params, ([key, value]) => [key.toLowerCase(), value])
);
Live example:
// The starting point from the question -- a URLSearchParams
// from "?someParam=paramValue"
const params = new URLSearchParams(
"?someParam=paramValue"
);
// The thing from the question that doesn't work
console.log(params.get("someparam"));
// ---- Solution:
// Create a new URLSearchParams with all the keys lower case
const newParams = new URLSearchParams(
Array.from(params, ([key, value]) => [key.toLowerCase(), value])
);
// Now using the lower case key works
console.log(newParams.get("someparam"));
You can create a custom function to get parameter value from location:
function getUrlParamValue(paramName){
var params = new URL(location).searchParams;
var keyName = Array.from(params.keys()).find(
function(key){
return key.toLowerCase() == paramName.toLowerCase();
}
);
return params.get(keyName);
}
Example: location = http://some.site.com/target?firstname=val
getUrlParamValue("FirstName") // returns val
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With