如何在encodeURIComponent(“+”)中保持+符号不变

How do I keep + sign as is in encodeURIComponent("+")?

本文关键字:符号 encodeURIComponent      更新时间:2023-09-26

在代码的一部分中,我无法更改。函数encodeURIComponent()将在我传入的URL上执行,我的任何一个API调用都包含一个+号,这是作为+号发送所必需的。现在它将替换使API失败的"%2B"。。

我尝试过使用转义和"%2B",并在+符号前面使用反斜杠作为"+",但到目前为止没有任何结果。。

如何使encodeURIComponent('+')返回+而不是"%2B"

感谢您的帮助

暂时将加号换成任意标记,例如

encodeURIComponent("one £ + £ two".replace(/'+/g, '*PLUS*')).replace('*PLUS*', '+');

给你:

"one%20%C2%A3%20+%20%C2%A3%20two"

即保留+,该+也将通过decodeURIComponent()在反向跳闸中幸存。

如果不更改代码,就无法做到这一点。encodeURIComponent永远不会输出+符号。

如果你或其他人可以更改代码,你可以使用这个答案:

encodeURIComponent(search).replace(/%20/g, "+");

然后在输入中使用您希望+所在的空格。

通常不建议覆盖本机函数,但您可以这样做,这将重新定义encodeURIComponent,使其不转义加号,而是转义同一组字符。

function encodeURIComponent(s) {
    // encodeURI leaves these chars untouched @#$&=:/,;?+
    return encodeURI(s).replace(/[@#$&=:'/,;?]/g, function(c) {
        return '%'+c.charCodeAt(0).toString(16)
    })
}

由于无法更改encodeURIComponent的行为,最简单的方法是将%2B-s替换回+-es:

encodeURIComponent('1+2=3').replace(/%2B/g, '+') //1+2%3D3

这更有效,因为它需要一次更换,而不需要中间的";"逃逸";,更简单,因为您不必重新实现encodeURIComponent,并且对于大型字符串,使用原生的可能会更快。