Skip to content

Commit

Permalink
Add .parseUrl() method (#104)
Browse files Browse the repository at this point in the history
  • Loading branch information
OrRosenblatt authored and sindresorhus committed Feb 3, 2018
1 parent 334152b commit 59d53d6
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
7 changes: 7 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,10 @@ exports.stringify = function (obj, opts) {
return x.length > 0;
}).join('&') : '';
};

exports.parseUrl = function (str, opts) {
return {
url: str.split('?')[0] || '',
query: this.parse(this.extract(str), opts)
};
};
14 changes: 14 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,20 @@ If omitted, keys are sorted using `Array#sort`, which means, converting them to
Extract a query string from a URL that can be passed into `.parse()`.


### .parseUrl(*string*, *[options]*)

Extract the URL and the query string as an object.

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

Returns an object with a `url` and `query` property.

```js
queryString.parseUrl('http://foo.bar?foo=bar')
//=> {url: 'http://foo.bar', query: {foo: 'bar'}}
```


## 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](https://github.com/visionmedia/node-querystring/issues).
Expand Down
17 changes: 17 additions & 0 deletions test/parse-url.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import test from 'ava';
import fn from '../';

test('should handle strings with query string', t => {
t.deepEqual(fn.parseUrl('http://foo.bar?foo=bar'), {url: 'http://foo.bar', query: {foo: 'bar'}});
t.deepEqual(fn.parseUrl('http://foo.bar?foo=bar&foo=baz'), {url: 'http://foo.bar', query: {foo: ['bar', 'baz']}});
});

test('should handle strings not containing query string', t => {
t.deepEqual(fn.parseUrl('http://foo.bar/'), {url: 'http://foo.bar/', query: {}});
t.deepEqual(fn.parseUrl(''), {url: '', query: {}});
});

test('should throw for invalid values', t => {
t.throws(fn.parseUrl.bind(fn, null), TypeError);
t.throws(fn.parseUrl.bind(fn, undefined), TypeError);
});

0 comments on commit 59d53d6

Please sign in to comment.