URL编码将“&”(&符号)视为“& amp;”HTML实体 [英] URL encode sees “&” (ampersand) as “&” HTML entity

查看:692
本文介绍了URL编码将“&”(&符号)视为“& amp;”HTML实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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

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

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

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

If that isn't the case, you can use the replace() method to replace the HTML entity:

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

这篇关于URL编码将“&”(&符号)视为“& amp;”HTML实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆