本文翻译自:URL encode sees “&” (ampersand) as “&” HTML entity
I am encoding a string that will be passed in a URL (via GET). 我正在编码一个将在URL中传递的字符串(通过GET)。 But if I use escape
, encodeURI
or encodeURIComponent
, &
will be replaced with %26amp%3B
, but I want it to be replaced with %26
. 但是如果我使用escape
, encodeURI
或encodeURIComponent
, &
将被替换为%26amp%3B
,但我希望它被替换为%26
。 What am I doing wrong? 我究竟做错了什么?
#1楼
参考:https://stackoom.com/question/ErMN/URL编码将-符号-视为-HTML实体
#2楼
There is HTML and URI encodings. 有HTML和URI编码。 &
is &
encoded in HTML while %26
is &
in URI encoding . 是&
HTML编码,而%26
是&
URI编码 。
So before URI encoding your string you might want to HTML decode and then URI encode it :) 所以在URI编码你的字符串之前,你可能想要HTML解码,然后对它进行URI编码:)
var div = document.createElement('div');
div.innerHTML = '&AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);
result %26AndOtherHTMLEncodedStuff
结果%26AndOtherHTMLEncodedStuff
Hope this saves you some time 希望这能为您节省一些时间
#3楼
If you did literally this: 如果你真的这样做:
encodeURIComponent('&')
Then the result is %26
, you can test it here . 然后结果是%26
, 你可以在这里测试它 。 Make sure the string you are encoding is just &
and not &
确保您编码的字符串只是 &
而不是&
to begin with...otherwise it is encoding correctly, which is likely the case. 开始...否则它正确编码,这可能是这种情况。 If you need a different result for some reason, you can do a .replace(/&/g,'&')
before the encoding. 如果由于某种原因需要不同的结果,可以在编码之前执行.replace(/&/g,'&')
。
#4楼
Without seeing your code, it's hard to answer other than a stab in the dark. 没有看到你的代码,除了在黑暗中刺伤之外,很难回答。 I would guess that the string you're passing to encodeURIComponent() , which is the correct method to use, is coming from the result of accessing the innerHTML property. 我猜你正在传递给encodeURIComponent()的字符串,这是正确使用的方法,来自访问innerHTML属性的结果。 The solution is to get the innerText / textContent property value instead: 解决方案是获取innerText / textContent属性值:
var str,
el = document.getElementById("myUrl");
if ("textContent" in el)
str = encodeURIComponent(el.textContent);
else
str = encodeURIComponent(el.innerText);
If that isn't the case, you can use the replace() method to replace the HTML entity: 如果不是这种情况,您可以使用replace()方法替换HTML实体:
encodeURIComponent(str.replace(/&/g, "&"));