Javascript , encodeURI failed to encode round bracket "("
Asked Answered
B

5

14

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

Bifacial answered 8/6, 2017 at 7:22 Comment(0)
B
15

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

Boyles answered 12/10, 2020 at 12:13 Comment(0)
C
10

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

Champollion answered 8/6, 2017 at 9:29 Comment(2)
Even encodeURIComponent() is not encoding this character w3schools.com/jsref/…Bifacial
Know that .replace() will only replace the first instance of "(". To replace all instances, use a regex or .split.join, such as res.replace(/\(/g, "%28") or res.split("(").join("%28")Rhaetic
O
4

Based on encodeURIComponent docs by Mozilla

encodeURIComponent escapes all characters except:

A-Z a-z 0-9 - _ . ! ~ * ' ( )

So, the only characters we don't want to scape are: A-Z a-z 0-9.

So this function does it:

function encodeUriAll(value) {
  return value.replace(/[^A-Za-z0-9]/g, c =>
    `%${c.charCodeAt(0).toString(16).toUpperCase()}`
  );
}
Octogenarian answered 20/1, 2022 at 17:17 Comment(0)
N
3

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;
}
Newcomb answered 8/6, 2017 at 7:34 Comment(0)
K
0

In my case this custom function works

function customEncode(str) {
    return encodeURIComponent(str)
        .replace(/[!'()*]/g, function(c) {
            return '%' + c.charCodeAt(0).toString(16);
        })
        .replace(/%25/g, '%'); // Replace %25 with %
}
Kirchner answered 3/4, 2024 at 6:6 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.