encodeURIComponent Escapes Query Values
encodeURIComponent escapes reserved characters per query value while encodeURI keeps URI structure intact, so every value gets component encoding.
Code
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 & rustInside 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
GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.URL Query String SerializerParse a URL query string into decoded key/value pairs or serialize key=value lines into a percent-encoded query string with duplicate-key detection.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.