How to get query string parameters as an object – JavaScript

If you want to access the location.search parameters with JavaScript and have a key / value object returned, here's a snippet for you:

/** * Avoid tag injections into URL params * @param {string} html * @param {HTMLElement} [tag] * @return {string} */ function getEscapedURLString(html, tag = document.createElement(`textarea`)) { tag.textContent = html return tag.innerHTML } /** * Returns a key value object of the given locationSearch expecting it to * be window.location.search * * E.g. ('?a=1&b=2') => {a: 1, b: 2} * * @param {string} [locationSearch] - normally window.location.search * @return {object} key value presentation of search params */ function getLocationSearchParameters(locationSearch) { const queryParameters = {} let nameValue if (!locationSearch || locationSearch === `?`) { return queryParameters } // remove '?' symbol at the beginning locationSearch.substr(1).split(`&`).forEach((searchPart) => { nameValue = searchPart.split(`=`) queryParameters[nameValue[0].toLowerCase()] = getEscapedURLString(nameValue[1]) }) return queryParameters }

How to use it

console.log( getLocationSearchParameters('?first=test&second=hello&third=world') );

Output

Object { first: "test", second: "hello", third: "world" }

Jest Unit Tests

I even have some unit tests for you, using Jest

describe(`getLocationSearchParameters`, () => { test(`should return the correct array given '?test1=a&test2=b'`, () => { const result = getLocationSearchParameters(`?test1=a&test2=b`) const expected = { test1: `a`, test2: `b` } expect(result).toEqual(expected) }) test(`should return empty object`, () => { const result = getLocationSearchParameters(`?`) expect(result).toEqual(expect.objectContaining({})) }) })

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*