Parse and stringify URL query strings

Overview

query-string

Parse and stringify URL query strings





Install

$ npm install query-string

This module targets Node.js 6 or later and the latest version of Chrome, Firefox, and Safari. If you want support for older browsers, or, if your project is using create-react-app v1, use version 5: npm install query-string@5.

Usage

const queryString = require('query-string');

console.log(location.search);
//=> '?foo=bar'

const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}

console.log(location.hash);
//=> '#token=bada55cafe'

const parsedHash = queryString.parse(location.hash);
console.log(parsedHash);
//=> {token: 'bada55cafe'}

parsed.foo = 'unicorn';
parsed.ilike = 'pizza';

const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza'

location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'

API

.parse(string, options?)

Parse a query string into an object. Leading ? or # are ignored, so you can pass location.search or location.hash directly.

The returned object is created with Object.create(null) and thus does not have a prototype.

options

Type: object

decode

Type: boolean
Default: true

Decode the keys and values. URL components are decoded with decode-uri-component.

arrayFormat

Type: string
Default: 'none'

  • 'bracket': Parse arrays with bracket representation:
const queryString = require('query-string');

queryString.parse('foo[]=1&foo[]=2&foo[]=3', {arrayFormat: 'bracket'});
//=> {foo: ['1', '2', '3']}
  • 'index': Parse arrays with index representation:
const queryString = require('query-string');

queryString.parse('foo[0]=1&foo[1]=2&foo[3]=3', {arrayFormat: 'index'});
//=> {foo: ['1', '2', '3']}
  • 'comma': Parse arrays with elements separated by comma:
const queryString = require('query-string');

queryString.parse('foo=1,2,3', {arrayFormat: 'comma'});
//=> {foo: ['1', '2', '3']}
  • 'separator': Parse arrays with elements separated by a custom character:
const queryString = require('query-string');

queryString.parse('foo=1|2|3', {arrayFormat: 'separator', arrayFormatSeparator: '|'});
//=> {foo: ['1', '2', '3']}
  • 'bracket-separator': Parse arrays (that are explicitly marked with brackets) with elements separated by a custom character:
const queryString = require('query-string');

queryString.parse('foo[]', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> {foo: []}

queryString.parse('foo[]=', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> {foo: ['']}

queryString.parse('foo[]=1', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> {foo: ['1']}

queryString.parse('foo[]=1|2|3', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> {foo: ['1', '2', '3']}

queryString.parse('foo[]=1||3|||6', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> {foo: ['1', '', 3, '', '', '6']}

queryString.parse('foo[]=1|2|3&bar=fluffy&baz[]=4', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> {foo: ['1', '2', '3'], bar: 'fluffy', baz:['4']}
  • 'none': Parse arrays with elements using duplicate keys:
const queryString = require('query-string');

queryString.parse('foo=1&foo=2&foo=3');
//=> {foo: ['1', '2', '3']}
arrayFormatSeparator

Type: string
Default: ','

The character used to separate array elements when using {arrayFormat: 'separator'}.

sort

Type: Function | boolean
Default: true

Supports both Function as a custom sorting function or false to disable sorting.

parseNumbers

Type: boolean
Default: false

const queryString = require('query-string');

queryString.parse('foo=1', {parseNumbers: true});
//=> {foo: 1}

Parse the value as a number type instead of string type if it's a number.

parseBooleans

Type: boolean
Default: false

const queryString = require('query-string');

queryString.parse('foo=true', {parseBooleans: true});
//=> {foo: true}

Parse the value as a boolean type instead of string type if it's a boolean.

.stringify(object, options?)

Stringify an object into a query string and sorting the keys.

options

Type: object

strict

Type: boolean
Default: true

Strictly encode URI components with strict-uri-encode. It uses encodeURIComponent if set to false. You probably don't care about this option.

encode

Type: boolean
Default: true

URL encode the keys and values.

arrayFormat

Type: string
Default: 'none'

  • 'bracket': Serialize arrays using bracket representation:
const queryString = require('query-string');

queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket'});
//=> 'foo[]=1&foo[]=2&foo[]=3'
  • 'index': Serialize arrays using index representation:
const queryString = require('query-string');

queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'index'});
//=> 'foo[0]=1&foo[1]=2&foo[2]=3'
  • 'comma': Serialize arrays by separating elements with comma:
const queryString = require('query-string');

queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'comma'});
//=> 'foo=1,2,3'

queryString.stringify({foo: [1, null, '']}, {arrayFormat: 'comma'});
//=> 'foo=1,,'
// Note that typing information for null values is lost
// and `.parse('foo=1,,')` would return `{foo: [1, '', '']}`.
  • 'separator': Serialize arrays by separating elements with a custom character:
const queryString = require('query-string');

queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'separator', arrayFormatSeparator: '|'});
//=> 'foo=1|2|3'
  • 'bracket-separator': Serialize arrays by explicitly post-fixing array names with brackets and separating elements with a custom character:
const queryString = require('query-string');

queryString.stringify({foo: []}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> 'foo[]'

queryString.stringify({foo: ['']}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> 'foo[]='

queryString.stringify({foo: [1]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> 'foo[]=1'

queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> 'foo[]=1|2|3'

queryString.stringify({foo: [1, '', 3, null, null, 6]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> 'foo[]=1||3|||6'

queryString.stringify({foo: [1, '', 3, null, null, 6]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|', skipNull: true});
//=> 'foo[]=1||3|6'

queryString.stringify({foo: [1, 2, 3], bar: 'fluffy', baz: [4]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> 'foo[]=1|2|3&bar=fluffy&baz[]=4'
  • 'none': Serialize arrays by using duplicate keys:
const queryString = require('query-string');

queryString.stringify({foo: [1, 2, 3]});
//=> 'foo=1&foo=2&foo=3'
arrayFormatSeparator

Type: string
Default: ','

The character used to separate array elements when using {arrayFormat: 'separator'}.

sort

Type: Function | boolean

Supports both Function as a custom sorting function or false to disable sorting.

const queryString = require('query-string');

const order = ['c', 'a', 'b'];

queryString.stringify({a: 1, b: 2, c: 3}, {
	sort: (a, b) => order.indexOf(a) - order.indexOf(b)
});
//=> 'c=3&a=1&b=2'
const queryString = require('query-string');

queryString.stringify({b: 1, c: 2, a: 3}, {sort: false});
//=> 'b=1&c=2&a=3'

If omitted, keys are sorted using Array#sort(), which means, converting them to strings and comparing strings in Unicode code point order.

skipNull

Skip keys with null as the value.

Note that keys with undefined as the value are always skipped.

Type: boolean
Default: false

const queryString = require('query-string');

queryString.stringify({a: 1, b: undefined, c: null, d: 4}, {
	skipNull: true
});
//=> 'a=1&d=4'
const queryString = require('query-string');

queryString.stringify({a: undefined, b: null}, {
	skipNull: true
});
//=> ''
skipEmptyString

Skip keys with an empty string as the value.

Type: boolean
Default: false

const queryString = require('query-string');

queryString.stringify({a: 1, b: '', c: '', d: 4}, {
	skipEmptyString: true
});
//=> 'a=1&d=4'
const queryString = require('query-string');

queryString.stringify({a: '', b: ''}, {
	skipEmptyString: true
});
//=> ''

.extract(string)

Extract a query string from a URL that can be passed into .parse().

Note: This behaviour can be changed with the skipNull option.

.parseUrl(string, options?)

Extract the URL and the query string as an object.

Returns an object with a url and query property.

If the parseFragmentIdentifier option is true, the object will also contain a fragmentIdentifier property.

const queryString = require('query-string');

queryString.parseUrl('https://foo.bar?foo=bar');
//=> {url: 'https://foo.bar', query: {foo: 'bar'}}

queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true});
//=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'}

options

Type: object

The options are the same as for .parse().

Extra options are as below.

parseFragmentIdentifier

Parse the fragment identifier from the URL.

Type: boolean
Default: false

const queryString = require('query-string');

queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true});
//=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'}

.stringifyUrl(object, options?)

Stringify an object into a URL with a query string and sorting the keys. The inverse of .parseUrl()

The options are the same as for .stringify().

Returns a string with the URL and a query string.

Query items in the query property overrides queries in the url property.

The fragmentIdentifier property overrides the fragment identifier in the url property.

queryString.stringifyUrl({url: 'https://foo.bar', query: {foo: 'bar'}});
//=> 'https://foo.bar?foo=bar'

queryString.stringifyUrl({url: 'https://foo.bar?foo=baz', query: {foo: 'bar'}});
//=> 'https://foo.bar?foo=bar'

queryString.stringifyUrl({
	url: 'https://foo.bar',
	query: {
		top: 'foo'
	},
	fragmentIdentifier: 'bar'
});
//=> 'https://foo.bar?top=foo#bar'

object

Type: object

url

Type: string

The URL to stringify.

query

Type: object

Query items to add to the URL.

.pick(url, keys, options?)

.pick(url, filter, options?)

Pick query parameters from a URL.

Returns a string with the new URL.

const queryString = require('query-string');

queryString.pick('https://foo.bar?foo=1&bar=2#hello', ['foo']);
//=> 'https://foo.bar?foo=1#hello'

queryString.pick('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true});
//=> 'https://foo.bar?bar=2#hello'

.exclude(url, keys, options?)

.exclude(url, filter, options?)

Exclude query parameters from a URL.

Returns a string with the new URL.

const queryString = require('query-string');

queryString.exclude('https://foo.bar?foo=1&bar=2#hello', ['foo']);
//=> 'https://foo.bar?bar=2#hello'

queryString.exclude('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true});
//=> 'https://foo.bar?foo=1#hello'

url

Type: string

The URL containing the query parameters to filter.

keys

Type: string[]

The names of the query parameters to filter based on the function used.

filter

Type: (key, value) => boolean

A filter predicate that will be provided the name of each query parameter and its value. The parseNumbers and parseBooleans options also affect value.

options

Type: object

Parse options and stringify options.

Nesting

This module intentionally doesn't support nesting as it's not spec'd and varies between implementations, which causes a lot of edge cases.

You're much better off just converting the object to a JSON string:

const queryString = require('query-string');

queryString.stringify({
	foo: 'bar',
	nested: JSON.stringify({
		unicorn: 'cake'
	})
});
//=> 'foo=bar&nested=%7B%22unicorn%22%3A%22cake%22%7D'

However, there is support for multiple instances of the same key:

const queryString = require('query-string');

queryString.parse('likes=cake&name=bob&likes=icecream');
//=> {likes: ['cake', 'icecream'], name: 'bob'}

queryString.stringify({color: ['taupe', 'chartreuse'], id: '515'});
//=> 'color=taupe&color=chartreuse&id=515'

Falsy values

Sometimes you want to unset a key, or maybe just make it present without assigning a value to it. Here is how falsy values are stringified:

const queryString = require('query-string');

queryString.stringify({foo: false});
//=> 'foo=false'

queryString.stringify({foo: null});
//=> 'foo'

queryString.stringify({foo: undefined});
//=> ''

query-string for enterprise

Available as part of the Tidelift Subscription.

The maintainers of query-string and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Comments
  • add method to get query string from url

    add method to get query string from url

    For convenience, it would be nice to have a method that can pluck the query string from a url:

    var qs = require("query-string");
    var url = "http://some.url/with?a=few&query=params";
    var query = qs.getQuery(url); // "?a=few&query=params"
    qs.parse(query); // { a : "few", query : "params" }
    
    opened by WickyNilliams 21
  • result from `parse` no longer has `hasOwnProperty` method

    result from `parse` no longer has `hasOwnProperty` method

    in 3.0.1, parse had the following behavior:

    > qs.parse('my-param=my-val')
    { 'my-param': 'my-val' }
    > qs.parse('my-param=my-val').hasOwnProperty
    [Function: hasOwnProperty]
    > qs.parse('h=j').hasOwnProperty
    [Function: hasOwnProperty]
    > qs.parse('').hasOwnProperty
    [Function: hasOwnProperty]
    

    in 3.0.2, the object returned no longer has the hasOwnProperty method:

    > qs.parse('hbud-fixture=not-logged-in')
    { 'hbud-fixture': 'not-logged-in' }
    > qs.parse('hbud-fixture=not-logged-in').hasOwnProperty
    undefined
    > qs.parse('hbudfixture=not-logged-in').hasOwnProperty
    undefined
    > qs.parse('hbudfixture=notloggedin').hasOwnProperty
    undefined
    > qs.parse('').hasOwnProperty
    [Function: hasOwnProperty]
    > qs.parse('h=j').hasOwnProperty
    undefined
    

    I am unsure whether this was considered part of the API, but some consumers rely on the behavior - https://github.com/mjackson/history/blob/master/modules/useQueries.js#L13

    opened by SpainTrain 18
  • Feature request: query-string strip (`pick`, `exclude`)

    Feature request: query-string strip (`pick`, `exclude`)

    To eliminate unneeded params, preserve only needed

    queryString.strip('http://example.com/?a=1&b=2', [ 'a' ] )
    // result : http://example.com/?a=1
    

    It would be helpful when page has many redudant params (like statistic params) and want to get a cleaner one


    Better function names from @Uzlopak:

    queryString.pick('http://example.com/?a=1&b=2', [ 'a' ] )
    // result : http://example.com/?a=1
    
    
    queryString.exclude('http://example.com/?a=1&b=2', [ 'a' ] )
    // result : http://example.com/?b=2
    
    enhancement help wanted 
    opened by zhangciwu 13
  • TypeError: decodeComponents(...).join is not a function

    TypeError: decodeComponents(...).join is not a function

    Version: v7.1.1

    Crash occured when # kun%ea%ba%5a%ba is parsed by queryString.parse This hash is valid and should be parsed correctly as { ' kun%ea%ba%5a%ba': null } For example in chrome's development tools' console the url https://google.com# kun%ea%ba%5a%ba can be parsed without problems:

    const url = new URL("https://google.com#  kun%ea%ba%5a%ba");
    url
    

    image

    Code to reproduce

    const queryString = require('query-string');
    
    const parsed = queryString.parse("#  kun%ea%ba%5a%ba");
    console.log(parsed);
    

    Results

    TypeError: decodeComponents(...).join is not a function

    opened by KatsuragiCSL 12
  • Add support for parsing/stringifying fragment identifier

    Add support for parsing/stringifying fragment identifier

    Fixes #220

    Add a new option parseFragment, which will provide the hash in the parseURL result. The new option is to prevent it from becoming a breaking change

    Seems Fragment Identifier is the technical jargon for it, let me know if it's ok or hash seems like a better choice

    cc\ @sindresorhus

    opened by Mark1626 12
  • Remove ampersand

    Remove ampersand

    Hi! If query string starts with &, result from parse will be { '': null, data: 'item' }

    console.log(query.parse("&data=item")); //{ '': null, data: 'item' }
    

    So, I've just a made more predictable behavior.

    console.log(query.parse("&data=item")); //{ data: 'item' }
    
    opened by saromanov 12
  • Property 'parse' does not exist on type 'typeof import(

    Property 'parse' does not exist on type 'typeof import("/xxx/frontend/node_modules/query-string/index")'

    Using the following code snippet I am getting a type error in v8.0.0

    import queryString from 'query-string';
    
    queryString.parse(window.location.search);
    
    opened by esetnik 11
  • stringifyUrl is not a function

    stringifyUrl is not a function

    Hello, I have an issue with stringifyUrl error. I couldn't find info about this anywhere so that's the reason i'm posting here.

    Screen Shot 2020-02-17 at 12 57 18 PM

    So this is a piece of code i'm trying to implement and in gives me this error. It is imported in this file like import queryString from 'query-string'

    Screen Shot 2020-02-17 at 12 57 08 PM

    The strange thing about this is when i paste the same code into online editor it all works as expected.

    Version of query-string is '6.11.0'.

    Thanks

    opened by utazabanje 11
  • Support stringifying objects into querystrings

    Support stringifying objects into querystrings

    For whatever reason, I need to send these kinds of query strings to a server:

    _embed=1&settings[prefetch]=false&settings[expiry]=3600

    I figured I'd use a similar data structure; a JavaScript object, and was a bit annoyed when stringifying {settings: { prefetch: false, expiry: 3600 }} resulted in an url encoded [object object].

    This fixes that. I added a new arrayFormat option, key.

    I tried giving a shot at parse, but we need one way conversion only at this point, and I couldn't figure it out in 10 minutes, so I gave up. Regular expressions are incomprehensible to me.

    opened by k1sul1 11
  • Undefined values are removed from stringified output

    Undefined values are removed from stringified output

    When stringifying an object where a value is undefined, previously the value would be passed along as 'undefined'. Now we remove it from the resulting query string entirely. This makes qs.stringify() more consistent with JSON.stringify().

    opened by tlhunter 11
  • Add support for `arrayFormat: 'bracket-separator'`

    Add support for `arrayFormat: 'bracket-separator'`

    The idea behind this format is to gain the advantages of short query strings that you have with comma and separator formats while marking a field as explicitly an array via a postfixed [] syntax.

    import queryString from 'query-string'
    
    queryString.stringify({ foo: ['one'] }, { arrayFormat: 'bracket-separator' })
    // => foo[]=one
    
    queryString.stringify({ foo: ['one', 'two', '', 'four' ] }, { arrayFormat: 'bracket-separator' })
    // => foo[]=one,two,,four
    
    queryString.stringify({ foo: ['one', 'two', '', 'four'] }, { arrayFormat: 'bracket-separator', arrayFormatSeparator: '|' })
    // => foo[]=one|two||four
    
    queryString.parse('?foo[]=one', { arrayFormat: 'bracket-separator' })
    // => {foo: ['one']
    
    queryString.parse('?foo[]=one,two,,four', { arrayFormat: 'bracket-separator' })
    // => {foo: ['one', 'two', '', 'four']}
    
    queryString.parse('?foo[]=one|two||four', { arrayFormat: 'bracket-separator', arrayFormatSeparator: '|' })
    // => {foo: ['one', 'two', '', 'four']}
    

    There are still are 2 question in regards to implementation:

    What should happen for {foo: []}? Currently, it would drop the parameter from the stringified query which is the same as {foo: null}

    This is undesirable personally. I feel like {foo: []} should produce ?foo[] unless I specify a flag to drop it. This would be a deviation from the ?bar&biz that non-arrays get the treatment of when they are null (no trailing =), but I feel like it makes sense as we have enough information to say, explicitly, that this is an array. Whereas if it were {foo: null} we don't know, explicitly, that this is an array, so it would produce ?foo which would mean that it would roundtrip correctly. However, the only way to produce this would be to change how the system is using Array.prototype.reduce as the reducer function is not ever invoked when the array is empty.

    What should happen for {foo: ['one', null, 'three']}. Currently it will drop the null and produce foo[]=one,three

    ~I haven't a strong opinion on this as it matches the functionality of separator. The only deviation from the separator functionality in regards to value dropping is that bracket-separator does not drop empty strings.~

    [Edit]: This has been changed to follow the skipNull and skipEmptyString options. As such, by default, null and '' will not be dropped. See https://github.com/sindresorhus/query-string/pull/304 for details. Thus, the following are true: | Input | Options | Output | | ------------- | ------------- | ------------ | | {foo: ['one', '', null, 'four']} | default settings | foo[]=one,,,four | | {foo: ['one', '', null, 'four']} | skipNull: true | foo[]=one,,four | | {foo: ['one', '', null, 'four']} | skipEmptyString true | foo[]=one,,four | | {foo: ['one', '', null, 'four']} | skipEmptyString true, skipNull: true | foo[]=one,four |

    opened by DV8FromTheWorld 10
  • How to encode entire string

    How to encode entire string

    When I am using queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'comma'}); the result is 'foo=1,2,3', is there a way to get the entire string encoded to 'foo%3D1%2C2%2C3', which is a result of encodeURIComponent('foo=1,2,3')?

    opened by oosharma 1
  • `pick` method returns the first match from a filter

    `pick` method returns the first match from a filter

    I am trying to clean a URL and only keep some parameters that I need in order to parse them so I was using pick method providing it the url, and the filter which is a regex test method here I am testing to check if the key in the query parameter matches the regular expression

    const groupRegex = new RegExp('^(GRP_)[a-zA-Z0-9/-]','g');
    export const parseGroups= (url:string)=>{
        let pickedURL = qs.pick(url,(key,value)=>groupRegex.test(key));
        console.log(pickedURL);
    }
    var url=`http://localhost:3000/tat?GRP_Bob[]=SW&GRP_sa[]=QW&GRP_sa[]=AA&projects[]=MP,PM&releases[]=2021.4,2022.1`
    parseGroups(url)
    

    for example http://localhost:3000/tat?GRP_Bob[]=SW&GRP_sa[]=QW&GRP_sa[]=AA&projects[]=MP,PM&releases[]=2021.4,2022.1 it should return http://localhost:3000/tat?GRP_Bob=SW&GRP_sa=QW&GRP_sa=AA yet it only tests for the first request parameter only and logs http://localhost:3000/tat?GRP_Bob%5B%5D=SW

    I am trying to clean the url from any other parameters that doesn't match my regular expression so I can parse the URL and extract the object so it can be like this for example

    {
           GRP_Bob:["SW"],
           GRP_sa:["QW","AA"]
     }
    

    Instead of having other parameters parsed also which are not necessary. I know I can just parse the url normally, and then loop on the returned query object, and remove any key that doesn't match the regex, but is there anything wrong I am doing in the above snippet?

    UPDATE: I changed the filter function to be (key,value)=>key.startsWith('GRP_'))

    export const parseGroups= (url:string)=>{
        let pickedURL = qs.pick(url,(key,value)=>key.startsWith('GRP_'));
        console.log(pickedURL);
        let parsedURL = qs.parseUrl(pickedURL)
        console.log(parsedURL.query)
    }
    var url=`http://localhost:3000/tat?GRP_Bob[]=SW&GRP_sa[]=QW&GRP_sa[]=AA&projects[]=MP,PM&releases[]=2021.4,2022.1`
    parseGroups(url)
    

    and the pickedURL logged this http://localhost:3000/tat?GRP_Bob%5B%5D=SW&GRP_sa%5B%5D=QW&GRP_sa%5B%5D=AA which is likely to be correct. it came out like that

    GRP_Bob[]: "SW"
    GRP_sa[]: (2) ['QW', 'AA']
    

    So I am confused actually what's going on with the regular expression approach, and why the keys in the second approach have [] in it?

    opened by shehabadel 2
  • Support `regex` for arrayFormat

    Support `regex` for arrayFormat

    I have an issue with array params url: 1. ?categoryIds=1&categoryIds=2 => categoryIds=['1', '2'] : Right 2. ?categoryIds=1 => categoryIds='1' : Wrong => Expect: categoryIds=['1'] Could you add regex option for arrayFormat ? Or everyone have a solution for this. Big thanks to you 🙇

    opened by phuhd-0935 3
  • Parsing array that contains elements whose contain encoded pipe char (%7C instead of '|')

    Parsing array that contains elements whose contain encoded pipe char (%7C instead of '|')

    Hello. I am trying to parse an array of elements separated by the pipe character '|'. The elements themselves might contain the pipe char, hence those should be encoded first (to %7C). With array of 2 elements or above it works just fine. However with array of one element it doesn't. My guess is that parse doesn't see explicitly pipe char, it decodes %7C into pipe char and creates array of 2 elements. (A side note: this method with other special characters works just fine.) please refer the following code example:

    // begin of code
    function TestQueryString(): void {
      const value1: string = encodeURIComponent('a|b'); 
      const twoElements = parse(`foo=${value1}|2`, {
        arrayFormat: 'separator',
        arrayFormatSeparator: '|',
      });
      console.log(twoElements); // Works as expected got: [ 'a|b', '2']
    
      const oneElement = parse(`bar=${value1}`, {
        arrayFormat: 'separator',
        arrayFormatSeparator: '|',
      });
      console.log(oneElement); // Here is the issue. Expected: 'a|b' but got [ 'a', 'b']
    }
    // end of code
    

    Screenshot with '|'. Not expected behavior in one element case: image

    Screenshot with '%'. Expected behavior as another special characters: image

    Thanks,

    opened by ShimShum2021 1
  • stringify with arrayFormat: 'brackets' doesn't urlEncode the square brackets

    stringify with arrayFormat: 'brackets' doesn't urlEncode the square brackets

    It seems keys generated from arrays with arrayFormat: 'bracket' don't get urlEncoded:

    stringify({ a: [1, 2, 3 ]}, { arrayFormat: 'bracket' }); => a[]=1&a[]=2&a[]=3

    opened by ioev 3
  • How I can exclude a member of array from Url?

    How I can exclude a member of array from Url?

    I want to exclude a value of an array from query string. How I can do this?

      const removeFilter = (filterKey, filterValue) => {
        const test = queryString.exclude(
          location.search,
          (key, value) => {
            return (
              key === filterKey &&
              (Array.isArray(value) ? value.includes(filterValue) : value === filterValue.toString())
            );
          },
          {
            arrayFormat: 'comma',
          }
        );
        history.push({ search: test });
      };
    
    opened by fpichlou 1
Releases(v8.1.0)
  • v8.1.0(Dec 20, 2022)

  • v8.0.3(Dec 14, 2022)

  • v8.0.2(Dec 13, 2022)

  • v8.0.1(Dec 13, 2022)

  • v8.0.0(Dec 12, 2022)

  • v7.1.3(Dec 2, 2022)

  • v7.1.2(Dec 1, 2022)

  • v7.1.1(Feb 5, 2022)

  • v7.1.0(Jan 6, 2022)

    • Add support for parameters with an explicit :list marker (#335) 6d220e6

    https://github.com/sindresorhus/query-string/compare/v7.0.1...v7.1.0

    Source code(tar.gz)
    Source code(zip)
  • v7.0.1(Jun 21, 2021)

    • Don't encode the fragment identifier in .pick and .exclude (#320) fd3e779

    https://github.com/sindresorhus/query-string/compare/v7.0.0...v7.0.1

    Source code(tar.gz)
    Source code(zip)
  • v7.0.0(Mar 18, 2021)

    Breaking

    • Implement skips for stringify array format comma (#304) 828f032
      • This is a breaking change to the default functionality of .stringify() for comma and separator array modes given that skipNull and skipEmptyString are default false but the original functionality of .stringify() for these 2 modes behaved as though skipNull and skipEmptyString were true.

    Improvements

    • Add support for arrayFormat: 'bracket-separator' (#276) b10bc19

    https://github.com/sindresorhus/query-string/compare/v6.14.1...v7.0.0

    Source code(tar.gz)
    Source code(zip)
  • v6.14.1(Feb 26, 2021)

  • v6.14.0(Feb 10, 2021)

  • v6.13.8(Dec 30, 2020)

  • v6.13.7(Nov 5, 2020)

    • Allow readonly Stringifiable[] in StringifiableRecord (#291) 71d84b7

    https://github.com/sindresorhus/query-string/compare/v6.13.6...v6.13.7

    Source code(tar.gz)
    Source code(zip)
  • v6.13.6(Oct 17, 2020)

    • When only receiving values with encoded array value, decode values (#287) b38f06c

    https://github.com/sindresorhus/query-string/compare/v6.13.5...v6.13.6

    Source code(tar.gz)
    Source code(zip)
  • v6.13.5(Oct 2, 2020)

    • Allow null and undefined in Stringifiable TypeScript type (#281) df4cbb3

    https://github.com/sindresorhus/query-string/compare/v6.13.4...v6.13.5

    Source code(tar.gz)
    Source code(zip)
  • v6.13.4(Sep 28, 2020)

    • Fix the TypeScript types for .stringify() and .stringifyUrl() (#279) 38906bc

    https://github.com/sindresorhus/query-string/compare/v6.13.3...v6.13.4

    Source code(tar.gz)
    Source code(zip)
  • v6.13.3(Sep 27, 2020)

  • v6.13.2(Sep 13, 2020)

  • v6.13.1(Jun 11, 2020)

    • Fix sorting existing query params in URL when sort option is false (#265) 549d677

    https://github.com/sindresorhus/query-string/compare/v6.13.0...v6.13.1

    Source code(tar.gz)
    Source code(zip)
  • v6.13.0(Jun 6, 2020)

  • v6.12.1(Apr 12, 2020)

    • Fix value being decoded twice with arrayFormat option set to separator (#243) 3b4c295

    https://github.com/sindresorhus/query-string/compare/v6.12.0...v6.12.1

    Source code(tar.gz)
    Source code(zip)
  • v6.12.0(Apr 6, 2020)

  • v6.11.1(Mar 2, 2020)

  • v6.11.0(Feb 13, 2020)

    • Support custom array separator (#234) 7712622
    • Preserve encoded commas when using arrayFormat: 'comma' (#236) a1d108f

    https://github.com/sindresorhus/query-string/compare/v6.10.1...v6.11.0

    Source code(tar.gz)
    Source code(zip)
  • v6.10.1(Jan 17, 2020)

  • v6.10.0(Jan 16, 2020)

  • v6.9.0(Nov 13, 2019)

    • Add option to skip keys with the value of null in .stringify() (#215) 20d8069
    • Only parse + to space when decode is true (#214) e20ab65

    https://github.com/sindresorhus/query-string/compare/v6.8.3...v6.9.0

    Source code(tar.gz)
    Source code(zip)
  • v6.8.3(Aug 31, 2019)

    • Make parseNumbers and parseBooleans options work with arrayFormat (#202) d2451aa

    https://github.com/sindresorhus/query-string/compare/v6.8.2...v6.8.3

    Source code(tar.gz)
    Source code(zip)
Owner
Sindre Sorhus
Full-Time Open-Sourcerer. Wants more empathy & kindness in open source. Focuses on Swift & JavaScript. Makes macOS apps, CLI tools, npm packages. Likes unicorns
Sindre Sorhus
Multiline strings in JavaScript

multiline Multiline strings in JavaScript No more string concatenation or array join! Use ES2015 template literals instead whenever possible. Before c

Sindre Sorhus 1.4k Dec 30, 2022
Javascript URL mutation library

URI.js About Understanding URIs Documentation jQuery URI Plugin Author Changelog IMPORTANT: You may not need URI.js anymore! Modern browsers provide t

Medialize 6.2k Dec 30, 2022
Lightweight URL manipulation with JavaScript

domurl 2.x (former jsurl) Lightweight URL manipulation with JavaScript for both DOM and server JavaScript. Goal To have a convenient way working with

Mykhailo Stadnyk 511 Dec 28, 2022
Belirlediğiniz Özel URL'yi her saniye dener ve alırsa belirlediğiniz kanala sizi etiketleyerek onay mesajı atar.

Novasy Url Spam Selam, bahsedilecek pek bir şey yok config.json dosyasını düzenledikten sonra kullanabilirsiniz. Bana ulaşabileceğiniz sosyal medya he

novasy 28 Dec 29, 2022
Backend para encurtar url utilizando o que aprendi no Ignite da Rocketseat.

?? URL Shortener ?? ?? Tecnologias | ?? Projeto | ?? Como executar | ?? Licença ?? Tecnologias Esse projeto foi desenvolvido com as seguintes tecnolog

Iago Beserra 4 Jan 25, 2022
Spec compliant URL state machine for Node.js

URL Parser This repository contains a work in progress state machine 100% compliant to the URL parser specification. The goal is to create a performan

Yagiz Nizipli 190 Dec 3, 2022
easier than regex string matching patterns for urls and other strings. turn strings into data or data into strings.

url-pattern easier than regex string matching patterns for urls and other strings. turn strings into data or data into strings. This is a great little

null 562 Jan 5, 2023
Simple JSON parse/stringify for the Wren programming language

wren-json Simple JSON parse/stringify for the Wren programming language. Parses strict json and relaxed json Comments Unquoted keys Trailing commas St

.ruby 8 May 18, 2022
Backend API Rest application for ShortLink, a URL shortening service where you enter a valid URL and get back an encoded URL

ShortLink - The Shortest URL (API) Sobre o Projeto | Como Usar | Importante! Sobre o projeto The Shortest URL é um projeto back-end de ShortLink, um s

Bruno Weber 2 Mar 22, 2022
This package will help parse OData strings (only the Microsoft Dataverse subset). It can be used as a validator, or you can build some javascript library which consumes the output of this library.

@albanian-xrm/dataverse-odata This package will help parse OData strings (only the Microsoft Dataverse subset). It can be used as a validator, or you

AlbanianXrm 3 Oct 22, 2022
A minimalistic yet efficient way to stringify and revive instances via JSON.

json-instances Social Media Photo by Francisco J. Villena on Unsplash A minimalistic yet efficient way to stringify and revive instances via JSON. If

Andrea Giammarchi 11 Jun 23, 2022
A simple query builder, it will helps to develop DSL query for Elasticsearch

Elasticsearch Dynamic Query Builder A simple query builder, it will helps to develop DSL query for elasticsearch Installation You can start it from np

Hashemi Rafsan 4 Nov 20, 2022
A library for creating typesafe standardized query keys, useful for cache management in @tanstack/query

Query Key Factory Typesafe query key management for @tanstack/query with auto-completion features. Focus on writing and invalidating queries without t

Luke Morales 446 Jan 3, 2023
URL query encoder/decoder with a user configuration

@lfgroup/query-coder URL query coder/decoder with configurable user pattern. It provides the most comfortable experience for encoding and decoding com

LF Group Inc. 14 Jul 14, 2022
Piccloud is a full-stack (Angular & Spring Boot) online image clipboard that lets you share images over the internet by generating a unique URL. Others can access the image via this URL.

Piccloud Piccloud is a full-stack application built with Angular & Spring Boot. It is an online image clipboard that lets you share images over the in

Olayinka Atobiloye 3 Dec 15, 2022
geotiff.js is a small library to parse TIFF files for visualization or analysis. It is written in pure JavaScript, and is usable in both the browser and node.js applications.

geotiff.js Read (geospatial) metadata and raw array data from a wide variety of different (Geo)TIFF files types. Features Currently available function

geotiff.js 649 Dec 21, 2022
A set of connectors to describe, parse and process the data sources provided by websites and social networks

HUDI-PACKAGE-CONNECTORS What is this repository for? A set of connectors to describe, parse and process the data sources provided by websites and soci

HUDI 8 Aug 5, 2022
Parse, validate, manipulate, and display dates in javascript.

Moment.js A JavaScript date library for parsing, validating, manipulating, and formatting dates. Project Status Moment.js is a legacy project, now in

Moment.js 47.1k Jan 2, 2023
Twitter Text Libraries. This code is used at Twitter to tokenize and parse text to meet the expectations for what can be used on the platform.

twitter-text This repository is a collection of libraries and conformance tests to standardize parsing of Tweet text. It synchronizes development, tes

Twitter 2.9k Jan 8, 2023
Github action to parse OWNERS files and outputs random reviewers

Get Owners Github Action Do you want to have all the approvers and reviewers without having strange scripts in your actions? Do you want to have rando

Ugo Palatucci 3 Oct 22, 2022