I have cookie value which contains round bracket " e.g: demo (1)" When I try to encode with encodeURI , the round bracket ( is not encoded to %28 , what is the alternative to encode the special characters like round brackets
encodeURI()
encodes special characters, except: , / ? : @ & = + $ #.
One can use encodeURIComponent()
to encode the above character.
You can write custom method to encode ( to %28.
Example :
var uri = "my test.asp?(name";
var res = encodeURI(uri);
res.replace("(", "%28");
As pointed out in the comment below, string#replace
will remove the first occurrence, one can use string#replaceAll
i.e. res.replaceAll("(", "%28")
or string#replace
with global flag i.e. res.replace(/\(/g, "%28")
to remove all occurrences.
const uri = "my test.asp?(n(a(m(e",
res = encodeURI(uri);
console.log(res.replaceAll("(", "%28"));
NOTE :
encodeURI()
will not encode: ~!@#$&*()=:/,;?+'
encodeURIComponent()
will not encode: ~!*()'
To encode uri components to be RFC 3986 -compliant - which encodes the characters !'()*
- you can use:
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
Taken from just before Examples-section at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
For reference, see: https://www.rfc-editor.org/rfc/rfc3986
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With