实现说明
raw、value、whole 定义在模块顶层,中间不经过函数作用域。
使用要点
- 每一步打印都带着自己的标签:
component:、whole uri:、decoded:。
常见问题
运行之前需要装什么吗?
不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件用顶层绑定保存自己的状态:raw、value、whole。
核心语句
const whole = encodeURI('/search?q=' + raw);
const value = encodeURIComponent(raw);
const raw = 'blue/olive & rust';
代码示例
const raw = 'blue/olive & rust';
// encodeURIComponent 面向单个参数值:& = / 都会转义
const value = encodeURIComponent(raw);
console.log('component:', value);
// encodeURI 面向完整地址:保留 & = / ? 等结构字符,只转义空格等
const whole = encodeURI('/search?q=' + raw);
console.log('whole uri:', whole);
// 解码端用对应的 decodeURIComponent 还原
console.log('decoded:', decodeURIComponent(value));
// + 不会被解码成空格:那是表单编码的约定,不是 URI 编码的一部分
console.log('plus stays:', decodeURIComponent('a+b'));
// 经典坑:拼查询串忘记逐段转义,& 被当成参数分隔符
console.log('unencoded query breaks:', '/search?q=' + raw);