C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: With encodeURIComponent, we convert valid URL characters to their encoded representation for use in a component (not a full URL).
JavaScript program that uses encodeURIComponent
var part = "c# bird & fish";
// The encodeURIComponent method will encode hash signs.
var result = encodeURIComponent(part);
console.log("ENCODE BEORE: " + part);
console.log("ENCODE AFTER: " + result);
Output
ENCODE BEORE: c# bird & fish
ENCODE AFTER: c%23%20bird%20%26%20fish
JavaScript program that uses encodeURI
var part = "f# example";
// The encodeURIComponent method will not encode some things.
// ... If you want those things encoded, use encodeURIComponent.
var result = encodeURI(part);
console.log("ENCODEURI: " + result);
Output
ENCODEURI: f#%20example
JavaScript program that uses decodeURI
var part = "c%23%20example";
// Use decodeURI and decodeURIComponent methods.
var result1 = decodeURI(part);
var result2 = decodeURIComponent(part);
console.log("DECODEURI: " + result1);
console.log("DECODEURICOMPONENT: " + result2);
Output
DECODEURI: c%23 example
DECODEURICOMPONENT: c# example
So: When possible, use encodeURIComponent to fix encodings. It is faster and simpler to use.