Javascript encodeURIComponent不编码单引号

时间:2012-06-05 11:52:04

标签: javascript

尝试一下:

encodeURIComponent("'@#$%^&");

如果您尝试此操作,您将看到除单引号外所有特殊字符都已编码。我可以使用什么函数对所有字符进行编码并使用PHP对其进行解码?

感谢。

6 个答案:

答案 0 :(得分:45)

我不确定你为什么要对它们进行编码。如果您只想转义单引号,则可以使用.replace(/'/g, "%27")。但是,好的参考是:

答案 1 :(得分:3)

您可以使用

function fixedEncodeURIComponent (str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, escape);
}

fixedEncodeURIComponent("'@#$%^&");

检查参考http://mdn.beonex.com/en/JavaScript/Reference/Global_Objects/encodeURIComponent.html

答案 2 :(得分:2)

我发现了一个从不错过任何角色的巧妙技巧。我告诉它取代一切都不接受。我是这样做的(URL编码):

function encode(w){return w.replace(/[^]/g,function(w){return '%'+w.charCodeAt(0).toString(16)})}



function encode(w){return w.replace(/[^]/g,function(w){return '%'+w.charCodeAt(0).toString(16)})}

loader.value = encode(document.body.innerHTML);

<textarea id=loader rows=11 cols=55>www.WHAK.com</textarea>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

只需自己尝试encodeURI()encodeURIComponent() ...

console.log(encodeURIComponent('@#$%^&*'));

输入:@#$%^&*。输出:%40%23%24%25%5E%26*。那么,等等,*怎么了?为什么不转换呢? TLDR:您实际上想要fixedEncodeURIComponent()fixedEncodeURI()。长篇小说...

encodeURIComponent() 请勿使用。 使用MDN encodeURIComponent() Documentation强调我的定义和解释的fixedEncodeURIComponent()

要严格遵守 RFC 3986(保留!,',(,)和*) ,即使这些字符没有正式的URI分隔符使用时,可以安全使用以下内容:

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

虽然我们在讨论主题,但也不要使用encodeURI()。 MDN也有自己的重写,如MDN encodeURI() Documentation所定义。引用他们的解释...

如果希望遵循URL的最新RFC3986,这会保留方括号(用于IPv6),因此在形成可能属于URL的内容(例如主机)时未进行方括号编码,则以下代码段可能帮助:

function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }

答案 4 :(得分:0)

正如@Bergi所写,你可以替换所有的字符:

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;
}

答案 5 :(得分:0)

您可以使用btoa()atob(),对给定的字符串进行编码和解码,包括单引号。