url(不常用)
https://github.com/defunctzombie/node-url
https://www.npmjs.com/package/url
url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
import { parse } from 'url';
const obj = parse('/api/rule?current=1&pageSize=20&sorter=%7B%7D&filter=%7B%7D', true);
// obj 结果如下
{
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?current=1&pageSize=20&sorter=%7B%7D&filter=%7B%7D',
query: {
current: '1',
pageSize: '20',
sorter: '{}',
filter: '{}'
},
pathname: '/api/rule',
path: '/api/rule?current=1&pageSize=20&sorter=%7B%7D&filter=%7B%7D',
href: '/api/rule?current=1&pageSize=20&sorter=%7B%7D&filter=%7B%7D'
}
qs
增加了一些安全性的查询字符串解析和序列化字符串的库
https://github.com/ljharb/qs
https://www.npmjs.com/package/qs
qs.parse
qs.parse(string, [options])
将 url 参数字符串(编码)转换为对象
qs.parse('a=1&b=2&c=&d=xxx&e'); // { a: 1, b: 2, c: '', d: xxx, e: '' }
qs.parse('a[]=b&a[]=c'); // { a: ['b', 'c'] }
qs.parse('a[1]=c&a[0]=b'); // { a: ['b', 'c'] }
qs.parse('a%5Bb%5D=c'); // 编码字符串 { a: { b: 'c' } }
qs.stringify
qs.stringify(object, [options])
将对象转换为 url 参数字符串
qs.stringify({ a: 'b', c: 'd' }); // 'a=b&c=d'
qs.stringify({ a: { b: 'c' } }); // 'a%5Bb%5D=c'; // 自动编码
function alphabeticalSort(a, b) {
return a.localeCompare(b);
}
qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: (a, b) => a.localeCompare(b) });
// 使用 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)
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'