Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript , encodeURI failed to encode round bracket "("

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

like image 740
Stin Avatar asked Jun 08 '17 07:06

Stin


2 Answers

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: ~!*()'

like image 173
Hassan Imam Avatar answered Oct 02 '22 23:10

Hassan Imam


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

like image 37
mtkopone Avatar answered Oct 02 '22 23:10

mtkopone