3. querystring
querystring.escape() ---编码
Querystring.unescape() ---escape的逆运算
Querystring.parse() ---解析路径,对象
Querystring.stringify() parse的逆运算,对象变成字符串
例子:
// 导入模块
const queryString = require('querystring');
const {URL} = require('url');
// 处理查询信息
let urlValue = 'http://www.test.com/search?wd=hello&q=你好世界';
const url = new URL(urlValue);
console.log(url.search);//?wd=hello&q=%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C
console.log(queryString.escape(url.search));
//%3Fwd%3Dhello%26q%3D%25E4%25BD%25A0%25E5%25A5%25BD%25E4%25B8%2596%25E7%2595%258C
console.log(queryString.unescape('%3Fwd%3Dhello%26q%3D%25E4%25BD%25A0%25E5%25A5%25BD%25E4%25B8%2596%25E7%2595%258C'));
//?wd=hello&q=%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C
console.log(queryString.parse(url.search));//输出带着?号:{ '?wd': 'hello', q: '你好世界' }
const sp = url.searchParams;
console.log(sp);//URLSearchParams { 'wd' => 'hello', 'q' => '你好世界' }
// 获取sp中的值
console.log(sp.get('wd'));
// 遍历sp信息
sp.forEach(function (val,key) {
console.log(key,val);//wd hello
//q 你好世界
});