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
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() 不会编码:~!*()'
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)
| 归档时间: |
|
| 查看次数: |
6068 次 |
| 最近记录: |