encodeURIComponent Escapes Query Values

encodeURIComponent escapes reserved characters per query value while encodeURI keeps URI structure intact, so every value gets component encoding.

JavascriptData Fetching

Code

javascriptsnippet
18 lines
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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

component: blue%2Folive%20%26%20rust
whole uri: /search?q=blue/olive%20&%20rust
decoded: blue/olive & rust
plus stays: a+b
unencoded query breaks: /search?q=blue/olive & rust

Inside the snippet

Top-level bindings raw, value, whole hold the demo state — nothing sits inside a function scope.

Putting it to use

The demo output is labeled (component:, whole uri:, decoded:), so every printed line maps back to its originating operation.

Core lines

const whole = encodeURI('/search?q=' + raw);
const value = encodeURIComponent(raw);
const raw = 'blue/olive & rust';

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Its state lives in module-level bindings: `raw`, `value`, `whole`.