Go's url.ParseQuery in TypeScript

✓ Verified: Go 1.23
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { ParseQuery } from 'locutus/golang/url/ParseQuery'.

Or with CommonJS: const { ParseQuery } = require('locutus/golang/url/ParseQuery')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1ParseQuery('a=1&b=2&b=3'){a: ['1'], b: ['2', '3']}
2ParseQuery('q=go+lang&x=%2B'){q: ['go lang'], x: ['+']}
3ParseQuery('empty=&flag'){empty: [''], flag: ['']}

Notes

  • Parses URL-encoded key/value pairs into arrays per key.

Dependencies

This function uses the following Locutus functions:

Here's what our current TypeScript equivalent to Go's url.ParseQuery looks like.

import { QueryUnescape } from './QueryUnescape.ts'

type QueryValues = Record<string, string[]>

export function ParseQuery(query: string): QueryValues {
// discuss at: https://locutus.io/golang/url/ParseQuery
// parity verified: Go 1.23
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Parses URL-encoded key/value pairs into arrays per key.
// example 1: ParseQuery('a=1&b=2&b=3')
// returns 1: {a: ['1'], b: ['2', '3']}
// example 2: ParseQuery('q=go+lang&x=%2B')
// returns 2: {q: ['go lang'], x: ['+']}
// example 3: ParseQuery('empty=&flag')
// returns 3: {empty: [''], flag: ['']}

const raw = String(query)
if (raw === '') {
return {}
}

const out: QueryValues = {}
const pairs = raw.split('&')

for (const pair of pairs) {
if (pair === '') {
continue
}

const separator = pair.indexOf('=')
const keyRaw = separator >= 0 ? pair.slice(0, separator) : pair
const valueRaw = separator >= 0 ? pair.slice(separator + 1) : ''
const key = QueryUnescape(keyRaw)
const value = QueryUnescape(valueRaw)

const existing = out[key]
if (existing) {
existing.push(value)
} else {
out[key] = [value]
}
}

return out
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


Help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.


« More Go url functions


Star