博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
URL编码将“&”(&符号)视为“&”HTML实体
阅读量:2289 次
发布时间:2019-05-09

本文共 2087 字,大约阅读时间需要 6 分钟。

本文翻译自:

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楼

参考:


#2楼

There is HTML and URI encodings. 有HTML和URI编码。 & is & while %26 is & in . &%26&

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 , . 然后结果是%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, "&"));

转载地址:http://kzjnb.baihongyu.com/

你可能感兴趣的文章
Foreign Language_english_语法分析_1
查看>>
Machine Learning_mahout_20news_caution
查看>>
R_bioinfomatics_heatmap
查看>>
8086_proteus_masm配置
查看>>
8086_proteus_all_dsn
查看>>
Other_2015 规划
查看>>
Music_stories_index
查看>>
music_悲催的键盘手
查看>>
Others_各行业优秀的人
查看>>
欢迎使用CSDN-markdown编辑器
查看>>
DeepLearning 知识点整理
查看>>
stdcall 标准winNTdll 编写 与 调用
查看>>
Android 搭建
查看>>
Java 配置
查看>>
多个Activity的完全退出
查看>>
自定义android控件
查看>>
tomcat c/s 三层架构
查看>>
代码_多进程_简单实例
查看>>
转载_消息机制
查看>>
代码_网络_FTP
查看>>