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


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


encodeURI only encodes reserved characters so this function should not be expected to encode parentheses.

You could write your own function to encode all the characters in the string, or just create a custom list of characters you want to encode.

Fiddle

function superEncodeURI(url) {

  var encodedStr = '', encodeChars = ["(", ")"];
  url = encodeURI(url);

  for(var i = 0, len = url.length; i < len; i++) {
    if (encodeChars.indexOf(url[i]) >= 0) {
        var hex = parseInt(url.charCodeAt(i)).toString(16);
        encodedStr += '%' + hex;
    }
    else {
        encodedStr += url[i];
    }
  }

  return encodedStr;
}