pub fn encode_uri_component(s: impl AsRef<str>) -> StringExpand description
Encodes a URI component, such as a path segment or query value.
This function is equivalent to JavaScript’s encodeURIComponent(). It performs
more aggressive encoding than encode_uri, encoding all characters except
unreserved characters.
§Preserved Characters
Only unreserved characters are passed through unchanged:
A-Z,a-z,0-9,-,_,.,!,~,*,',(,)
All other characters, including reserved URI characters like /, ?, &, =,
are percent-encoded.
§Use Cases
Use this function when encoding values that will become part of a URL:
- Path segments
- Query parameter names and values
- Fragment identifiers
- Any user-provided input that will be embedded in a URL
§Examples
use uri_encode::encode_uri_component;
// Reserved characters are encoded
assert_eq!(encode_uri_component("a/b?c=d"), "a%2fb%3fc%3dd");
// Useful for query values
let search = "hello world";
let url = format!("https://example.com/search?q={}", encode_uri_component(search));
assert_eq!(url, "https://example.com/search?q=hello%20world");
// Handles special characters safely
assert_eq!(encode_uri_component("<script>"), "%3cscript%3e");