Skip to content

Commit 59d53d6

Browse files
OrRosenblattsindresorhus
authored andcommitted
Add .parseUrl() method (#104)
1 parent 334152b commit 59d53d6

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

index.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,3 +212,10 @@ exports.stringify = function (obj, opts) {
212212
return x.length > 0;
213213
}).join('&') : '';
214214
};
215+
216+
exports.parseUrl = function (str, opts) {
217+
return {
218+
url: str.split('?')[0] || '',
219+
query: this.parse(this.extract(str), opts)
220+
};
221+
};

readme.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,20 @@ If omitted, keys are sorted using `Array#sort`, which means, converting them to
163163
Extract a query string from a URL that can be passed into `.parse()`.
164164

165165

166+
### .parseUrl(*string*, *[options]*)
167+
168+
Extract the URL and the query string as an object.
169+
170+
The `options` are the same as for `.parse()`.
171+
172+
Returns an object with a `url` and `query` property.
173+
174+
```js
175+
queryString.parseUrl('http://foo.bar?foo=bar')
176+
//=> {url: 'http://foo.bar', query: {foo: 'bar'}}
177+
```
178+
179+
166180
## Nesting
167181

168182
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).

test/parse-url.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import test from 'ava';
2+
import fn from '../';
3+
4+
test('should handle strings with query string', t => {
5+
t.deepEqual(fn.parseUrl('http://foo.bar?foo=bar'), {url: 'http://foo.bar', query: {foo: 'bar'}});
6+
t.deepEqual(fn.parseUrl('http://foo.bar?foo=bar&foo=baz'), {url: 'http://foo.bar', query: {foo: ['bar', 'baz']}});
7+
});
8+
9+
test('should handle strings not containing query string', t => {
10+
t.deepEqual(fn.parseUrl('http://foo.bar/'), {url: 'http://foo.bar/', query: {}});
11+
t.deepEqual(fn.parseUrl(''), {url: '', query: {}});
12+
});
13+
14+
test('should throw for invalid values', t => {
15+
t.throws(fn.parseUrl.bind(fn, null), TypeError);
16+
t.throws(fn.parseUrl.bind(fn, undefined), TypeError);
17+
});

0 commit comments

Comments
 (0)