我正在编码一个将在 URL 中传递的字符串(通过 GET)。但是如果我使用escape
, encodeURI
or encodeURIComponent
,&
会被替换为%26amp%3B
,但我希望它被替换为%26
。我究竟做错了什么?
URL 编码将“&”(与号)视为“&” HTML 实体
IT技术
javascript
urlencode
2021-01-31 06:29:57
3个回答
没有看到你的代码,除了在黑暗中刺伤之外,很难回答。我猜你传递给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, "&"));
如果你真的这样做:
encodeURIComponent('&')
那么结果就是%26
,你可以在这里测试一下。确保您正在编码的字符串只是 &
而不是&
开始...否则它编码正确,这很可能是这种情况。如果由于某种原因需要不同的结果,则可以.replace(/&/g,'&')
在编码之前执行 a 。
有 HTML 和 URI 编码。&
是&
在HTML编码而%26
是&
在URI编码。
因此,在对字符串进行 URI 编码之前,您可能需要先进行 HTML 解码,然后再进行 URI 编码:)
var div = document.createElement('div');
div.innerHTML = '&AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);
结果 %26AndOtherHTMLEncodedStuff
希望这可以为您节省一些时间