Javascript ,encodeURI 未能编码圆括号“(”

Sti*_*tin 4 javascript uri encoder

我有包含圆括号“例如:演示(1)”的cookie值

mtk*_*one 14

要将 uri 组件编码为符合 RFC 3986(对字符进行编码)!'()*,您可以使用:

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}
Run Code Online (Sandbox Code Playgroud)

摘自示例部分之前:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

有关参考,请参阅:https ://www.rfc-editor.org/rfc/rfc3986


Has*_*mam 7

encodeURI()编码特殊字符,除了: , / ? :@ & = + $ #。可以使用encodeURIComponent()对上述字符进行编码。

您可以编写自定义方法来编码 ( 到 %28.

例子 :

var uri = "my test.asp?(name";
var res = encodeURI(uri);
res.replace("(", "%28");
Run Code Online (Sandbox Code Playgroud)

正如在下面的评论中指出的那样,string#replace将删除第一次出现,可以使用string#replaceAllieres.replaceAll("(", "%28")string#replace使用全局标志 ieres.replace(/\(/g, "%28") 来删除所有出现。

var uri = "my test.asp?(name";
var res = encodeURI(uri);
res.replace("(", "%28");
Run Code Online (Sandbox Code Playgroud)

注意: encodeURI()不会编码:~!@#$&*()=:/,;?+'

encodeURIComponent() 不会编码:~!*()'

  • 要知道 .replace() 只会替换“(”的第一个实例。要替换所有实例,请使用正则表达式或 .split.join,例如 `res.replace(/\(/g, "%28")`或 `res.split("(").join("%28")` (2认同)

Wil*_*ese 3

encodeURI仅对保留字符进行编码,因此不应期望此函数对括号进行编码。

您可以编写自己的函数来对字符串中的所有字符进行编码,或者只是创建要编码的自定义字符列表。

小提琴

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;
}
Run Code Online (Sandbox Code Playgroud)