我正在编码一个字符串,将在URL中传递(通过GET)。但如果我使用转义,encodeURI或encodeURIComponent, &将被%26amp%3B取代,但我希望它被%26取代。我做错了什么?


如果你真的这么做了:

encodeURIComponent('&')

然后结果是%26,您可以在这里测试它。确保你正在编码的字符串是&而不是&首先……否则,编码是正确的,这是可能的情况。如果出于某种原因需要不同的结果,可以在编码之前执行.replace(/&/g,'&')。

在没有看到代码的情况下,除了在黑暗中摸索之外,很难回答问题。我猜您传递给encodeURIComponent()的字符串(这是正确的方法)来自访问innerHTML属性的结果。解决方案是获得innerText/textContent属性值:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

如果不是这样,你可以使用replace()方法替换HTML实体:

encodeURIComponent(str.replace(/&/g, "&"));

有HTML和URI编码。,在HTML中是&编码,而在URI编码中%26是&编码。

所以在URI编码字符串之前,你可能想要HTML解码,然后URI编码它:)

var div = document.createElement('div'); div.innerHTML = '&AndOtherHTMLEncodedStuff'; var htmlDecoded=div.firstChild.nodeValue; console.log('htmlDecoded: '+htmlDecoded); var urlEncoded=encodeURIComponent(htmlDecoded); console.log('urlEncoded: '+urlEncoded);

结果% 26 andotherhtmlencodedstuff

希望这能为您节省一些时间

明确一点,永远不要使用encodeURI()和encodeURIComponent()。如果你不同意,看看结果…

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

输入:^ & *。 输出:% 40% 23% 24% 25% 5 e % 26 *。

这不对,是吗?*没有被转换!我希望您不是将其用作服务器端清理函数,因为*不会被视为输入,而是作为命令,例如,想象一下使用rm *删除用户所谓的文件。好吧,我希望你没有使用encodeURI()或encodeURIComponent()!

TLDR:你实际上需要fixedEncodeURIComponent()和fixedEncodeURI()。

MDN encodeURI()文档…

函数fixedEncodeURI(str) { 返回encodeURI (str)。replace (/ 5B / g,“[”)。replace (/ 5D / g、“]”); }

MDN encodeURIComponent()文档…

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

对于这些函数,使用fixedEncodeURI()来编码单个URL片段,而fixedEncodeURIComponent()将编码URL片段和连接器;或者,更简单地说,fixedEncodeURI()不会编码+@?=:#;,$&(因为&和+是常见的URL操作符),但fixedEncodeURIComponent()会。