javascriptreactjsquery-string

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?


Solution

  • 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"));