Javascript encodeURIComponent doesn't encode single quotes
尝试一下:
1 | encodeURIComponent("'@#$%^&"); |
如果您尝试此操作,您将看到除单引号外的所有特殊字符均已编码。我可以使用什么功能来编码所有字符并使用PHP对其进行解码?
谢谢。
我不确定为什么要对它们进行编码。如果只想转义单引号,则可以使用
- 什么时候应该使用转义而不是encodeURI / encodeURIComponent?
- 在xkr.us上比较escape(),encodeURI()和encodeURIComponent()
- Javascript Madness:查询字符串解析#Javascript编码/解码功能
您可以使用:
1 2 3 4 5 | function fixedEncodeURIComponent (str) { return encodeURIComponent(str).replace(/[!'()*]/g, escape); } fixedEncodeURIComponent("'@#$%^&"); |
检查参考:http://mdn.beonex.com/en/JavaScript/Reference/Global_Objects/encodeURIComponent.html
我发现了一个绝不会错过任何角色的巧妙技巧。我告诉它取代一切,什么都没有。我这样做(URL编码):
1 | function encode(w){return w.replace(/[^]/g,function(w){return '%'+w.charCodeAt(0).toString(16)})} |
1 2 3 | function encode(w){return w.replace(/[^]/g,function(w){return '%'+w.charCodeAt(0).toString(16)})} loader.value = encode(document.body.innerHTML); |
1 | <textarea id=loader rows=11 cols=55>www.WHAK.com</textarea> |
只需自己尝试
1 | console.log(encodeURIComponent('@#$%^&*')); |
输入:
To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
虽然我们在讨论主题,但也不要使用
If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }
您可以使用
正如@Bergi所写,您可以替换所有字符:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function encoePicture(pictureUrl) { var map= { '&': '%26', '<': '%3c', '>': '%3e', '"': '%22', "'": '%27' }; var encodedPic = encodeURI(pictureUrl); var result = encodedPic.replace(/[&<>"']/g, function(m) { return map[m];}); return result; } |