Skip to content

Commit

Permalink
Add a sortQueryParameters option (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanSanchez authored and sindresorhus committed Nov 30, 2017
1 parent 48b1864 commit b125e29
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
7 changes: 5 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ module.exports = (str, opts) => {
stripWWW: true,
removeQueryParameters: [/^utm_\w+/i],
removeTrailingSlash: true,
removeDirectoryIndex: false
removeDirectoryIndex: false,
sortQueryParameters: true
}, opts);

if (typeof str !== 'string') {
Expand Down Expand Up @@ -136,7 +137,9 @@ module.exports = (str, opts) => {
}

// Sort query parameters
urlObj.search = queryString.stringify(sortKeys(queryParameters));
if (opts.sortQueryParameters) {
urlObj.search = queryString.stringify(sortKeys(queryParameters));
}

// Decode query parameters
urlObj.search = decodeURIComponent(urlObj.search);
Expand Down
13 changes: 13 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,19 @@ normalizeUrl('www.sindresorhus.com/foo/default.php', {
//=> 'http://sindresorhus.com/foo'
```

##### sortQueryParameters

Type: `boolean`<br>
Default: `true`

Sort the query parameters alphabetically by key.

```js
normalizeUrl('www.sindresorhus.com?b=two&a=one&c=three', {
sortQueryParameters: true
});
//=> 'www.sindresorhus.com?a=one&b=two&c=three'
```

## Related

Expand Down
17 changes: 17 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,20 @@ test('removeTrailingSlash and removeDirectoryIndex options)', t => {
t.is(m('http://sindresorhus.com/path/', opts2), 'http://sindresorhus.com/path/');
t.is(m('http://sindresorhus.com/path/index.html', opts2), 'http://sindresorhus.com/path/');
});

test('sortQueryParameters option', t => {
let opts = {
sortQueryParameters: true
};
t.is(m('http://sindresorhus.com/?a=Z&b=Y&c=X&d=W', opts), 'http://sindresorhus.com/?a=Z&b=Y&c=X&d=W');
t.is(m('http://sindresorhus.com/?b=Y&c=X&a=Z&d=W', opts), 'http://sindresorhus.com/?a=Z&b=Y&c=X&d=W');
t.is(m('http://sindresorhus.com/?a=Z&d=W&b=Y&c=X', opts), 'http://sindresorhus.com/?a=Z&b=Y&c=X&d=W');

opts = {
sortQueryParameters: false
};

t.is(m('http://sindresorhus.com/?a=Z&b=Y&c=X&d=W', opts), 'http://sindresorhus.com/?a=Z&b=Y&c=X&d=W');
t.is(m('http://sindresorhus.com/?b=Y&c=X&a=Z&d=W', opts), 'http://sindresorhus.com/?b=Y&c=X&a=Z&d=W');
t.is(m('http://sindresorhus.com/?a=Z&d=W&b=Y&c=X', opts), 'http://sindresorhus.com/?a=Z&d=W&b=Y&c=X');
});

0 comments on commit b125e29

Please sign in to comment.