Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can URLSearchParams get param case insensitive?

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?

like image 506
goscamp Avatar asked Dec 06 '25 17:12

goscamp


2 Answers

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"));
like image 116
T.J. Crowder Avatar answered Dec 08 '25 05:12

T.J. Crowder


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
like image 31
boubkhaled Avatar answered Dec 08 '25 05:12

boubkhaled



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!