url(不常用)

https://github.com/defunctzombie/node-url
https://www.npmjs.com/package/url

url.parse(urlStr, [parseQueryString], [slashesDenoteHost])

  1. import { parse } from 'url';
  2. const obj = parse('/api/rule?current=1&pageSize=20&sorter=%7B%7D&filter=%7B%7D', true);
  3. // obj 结果如下
  4. {
  5. protocol: null,
  6. slashes: null,
  7. auth: null,
  8. host: null,
  9. port: null,
  10. hostname: null,
  11. hash: null,
  12. search: '?current=1&pageSize=20&sorter=%7B%7D&filter=%7B%7D',
  13. query: {
  14. current: '1',
  15. pageSize: '20',
  16. sorter: '{}',
  17. filter: '{}'
  18. },
  19. pathname: '/api/rule',
  20. path: '/api/rule?current=1&pageSize=20&sorter=%7B%7D&filter=%7B%7D',
  21. href: '/api/rule?current=1&pageSize=20&sorter=%7B%7D&filter=%7B%7D'
  22. }

qs

增加了一些安全性的查询字符串解析和序列化字符串的库
https://github.com/ljharb/qs
https://www.npmjs.com/package/qs

qs.parse

qs.parse(string, [options]) 将 url 参数字符串(编码)转换为对象

  1. qs.parse('a=1&b=2&c=&d=xxx&e'); // { a: 1, b: 2, c: '', d: xxx, e: '' }
  2. qs.parse('a[]=b&a[]=c'); // { a: ['b', 'c'] }
  3. qs.parse('a[1]=c&a[0]=b'); // { a: ['b', 'c'] }
  4. qs.parse('a%5Bb%5D=c'); // 编码字符串 { a: { b: 'c' } }

qs.stringify

qs.stringify(object, [options]) 将对象转换为 url 参数字符串

  1. qs.stringify({ a: 'b', c: 'd' }); // 'a=b&c=d'
  2. qs.stringify({ a: { b: 'c' } }); // 'a%5Bb%5D=c'; // 自动编码
  3. function alphabeticalSort(a, b) {
  4. return a.localeCompare(b);
  5. }
  6. qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: (a, b) => a.localeCompare(b) });
  7. // 使用 sort 进行排序 'a=c&b=f&z=y'

query-string

解析和字符串化 url
https://github.com/sindresorhus/query-string
https://www.npmjs.com/package/query-string

用法(parse, stringify)

  1. const queryString = require('query-string');
  2. console.log(location.search);
  3. //=> '?foo=bar'
  4. const parsed = queryString.parse(location.search);
  5. console.log(parsed);
  6. //=> {foo: 'bar'}
  7. console.log(location.hash);
  8. //=> '#token=bada55cafe'
  9. const parsedHash = queryString.parse(location.hash);
  10. console.log(parsedHash);
  11. //=> {token: 'bada55cafe'}
  12. parsed.foo = 'unicorn';
  13. parsed.ilike = 'pizza';
  14. const stringified = queryString.stringify(parsed);
  15. //=> 'foo=unicorn&ilike=pizza'
  16. location.search = stringified;
  17. // note that `location.search` automatically prepends a question mark
  18. console.log(location.search);
  19. //=> '?foo=unicorn&ilike=pizza'