我正在编码一个字符串,将在URL中传递(通过GET)。但如果我使用转义,encodeURI或encodeURIComponent, &将被%26amp%3B取代,但我希望它被%26取代。我做错了什么?
如果你真的这么做了:
encodeURIComponent('&')
然后结果是%26,您可以在这里测试它。确保你正在编码的字符串是&而不是&首先……否则,编码是正确的,这是可能的情况。如果出于某种原因需要不同的结果,可以在编码之前执行.replace(/&/g,'&')。
在没有看到代码的情况下,除了在黑暗中摸索之外,很难回答问题。我猜您传递给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, "&"));
有HTML和URI编码。,在HTML中是&编码,而在URI编码中%26是&编码。
所以在URI编码字符串之前,你可能想要HTML解码,然后URI编码它:)
var div = document.createElement('div'); div.innerHTML = '&AndOtherHTMLEncodedStuff'; var htmlDecoded=div.firstChild.nodeValue; console.log('htmlDecoded: '+htmlDecoded); var urlEncoded=encodeURIComponent(htmlDecoded); console.log('urlEncoded: '+urlEncoded);
结果% 26 andotherhtmlencodedstuff
希望这能为您节省一些时间
明确一点,永远不要使用encodeURI()和encodeURIComponent()。如果你不同意,看看结果…
console . log (encodeURIComponent ('@#$%^&*'));
输入:^ & *。 输出:% 40% 23% 24% 25% 5 e % 26 *。
这不对,是吗?*没有被转换!我希望您不是将其用作服务器端清理函数,因为*不会被视为输入,而是作为命令,例如,想象一下使用rm *删除用户所谓的文件。好吧,我希望你没有使用encodeURI()或encodeURIComponent()!
TLDR:你实际上需要fixedEncodeURIComponent()和fixedEncodeURI()。
MDN encodeURI()文档…
函数fixedEncodeURI(str) { 返回encodeURI (str)。replace (/ 5B / g,“[”)。replace (/ 5D / g、“]”); }
MDN encodeURIComponent()文档…
函数fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { 返回'%' + c.charCodeAt(0).toString(16); }); }
对于这些函数,使用fixedEncodeURI()来编码单个URL片段,而fixedEncodeURIComponent()将编码URL片段和连接器;或者,更简单地说,fixedEncodeURI()不会编码+@?=:#;,$&(因为&和+是常见的URL操作符),但fixedEncodeURIComponent()会。
推荐文章
- 将lodash导入到angular + typescript应用程序中
- 什么时候使用setAttribute vs .attribute=在JavaScript?
- 每60秒调用一个函数
- 我如何上传一个文件与JS获取API?
- 在JavaScript中是否有一个“not in”操作符来检查对象属性?
- 我如何能得到滚动条的位置与JavaScript?
- JavaScript中的yield关键字是什么?
- 如何显示一个对象的所有方法?
- .js和.mjs文件有什么区别?
- Axios处理错误
- ESLint解析错误:意外的令牌
- 同时映射和过滤一个数组
- TypeScript:创建一个空的类型容器数组
- 在JavaScript中将大字符串分割为n大小的块
- 如何从JavaScript字符串中剥离HTML标签?