我正在编码一个将在 URL 中传递的字符串(通过 GET)。但是如果我使用 escape
、encodeURI
或 encodeURIComponent
,&
将被替换为 %26amp%3B
,但我希望将其替换为 %26
。我做错了什么?
最佳答案
没有看到您的代码,除了在黑暗中刺伤之外,很难回答。我猜您传递给 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, "&"));
关于javascript - URL 编码将 “&”(和号)视为 “&” HTML 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3541711/