Javascript encodeURIComponent 不编码单引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10896807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:29:08  来源:igfitidea点击:

Javascript encodeURIComponent doesn't encode single quotes

javascript

提问by Ilya Karnaukhov

Try it out:

试试看:

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

If you try this out you will see all the special characters are encoded except for the single quote. What function can I use to encode ALL the characters and use PHP to decode them?

如果你试试这个,你会看到除了单引号之外的所有特殊字符都被编码了。我可以使用什么函数对所有字符进行编码并使用 PHP 对其进行解码?

Thanks.

谢谢。

回答by Bergi

I'm not sure why you would want them to be encoded. If you only want to escape single quotes, you could use .replace(/'/g, "%27"). However, good references are:

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

回答by Biswajit Maji

You can use

您可以使用

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

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

check reference http://mdn.beonex.com/en/JavaScript/Reference/Global_Objects/encodeURIComponent.html

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

回答by Dave Brown

I found a neat trick that never misses any characters. I tell it to replace everything accept for nothing. I do it like this (URL encoding):

我找到了一个绝不会错过任何字符的巧妙技巧。我告诉它替换一切都无所适从。我这样做(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>

回答by neomib

As @Bergi wrote u can just replace all the characters:

正如@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;
}

回答by Karthik Ashwin

You can use btoa() and atob(), this encodes and decodes the given string including single quote.

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