pub fn encode_uri(s: impl AsRef<str>) -> StringExpand description
Encodes a complete URI, preserving its structural characters.
This function is equivalent to JavaScript’s encodeURI(). It encodes all characters
except those that are valid in a URI, including reserved characters that have special
meaning in URI syntax.
§Preserved Characters
The following characters are passed through unchanged:
- Unreserved:
A-Z,a-z,0-9,-,_,.,!,~,*,',(,) - Reserved:
;,,,/,?,:,@,&,=,+,$,#
All other characters are percent-encoded.
§Use Cases
Use this function when you have a complete URL and want to ensure any unsafe characters (like spaces) are encoded while preserving the URL’s structure.
§Examples
use uri_encode::encode_uri;
// Spaces are encoded, but URL structure is preserved
assert_eq!(
encode_uri("https://example.com/hello world?name=foo bar"),
"https://example.com/hello%20world?name=foo%20bar"
);
// Reserved characters are preserved
assert_eq!(encode_uri("a/b?c=d&e=f"), "a/b?c=d&e=f");
// Non-ASCII characters are encoded
assert_eq!(encode_uri("café"), "caf%c3%a9");