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

本文翻译自: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 . 但是如果我使用escapeencodeURIencodeURIComponent&将被替换为%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, "&"));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值