Javascript URL 编码将“&”(与号)视为“&” HTML 实体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3541711/
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-23 05:05:24  来源:igfitidea点击:

URL encode sees “&” (ampersand) as “&” HTML entity

javascripturlencode

提问by dododedodonl

I am encoding a string that will be passed in a URL (via GET). But if I use escape, encodeURIor encodeURIComponent, &will be replaced with %26amp%3B, but I want it to be replaced with %26. What am I doing wrong?

我正在编码一个将在 URL 中传递的字符串(通过 GET)。但是如果我使用escape, encodeURIor encodeURIComponent,&会被替换为%26amp%3B,但我希望它被替换为%26。我究竟做错了什么?

回答by Andy E

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 innerHTMLproperty. The solution is to get the innerText/textContentproperty value instead:

没有看到你的代码,除了在黑暗中刺伤之外,很难回答。我猜想您传递给encodeURIComponent()的字符串是正确的使用方法,它来自访问innerHTML属性的结果。解决方案是获取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, "&"));

回答by Nick Craver

If you did literally this:

如果你真的这样做:

encodeURIComponent('&')

Then the result is %26, you can test it here. 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.

那么结果就是%26你可以在这里测试一下。确保您正在编码的字符串只是&而不是&开始...否则它编码正确,这很可能是这种情况。如果由于某种原因需要不同的结果,则可以.replace(/&/g,'&')在编码之前执行 a 。

回答by Matas Vaitkevicius

There is HTML and URI encodings. &is &encoded in HTMLwhile %26is &in URI encoding.

有 HTML 和 URI 编码。&&在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

希望这可以为您节省一些时间