【问题标题】:How do I keep + sign as is in encodeURIComponent("+")?如何在 encodeURIComponent("+") 中保持 + 符号?
【发布时间】:2020-12-02 03:22:20
【问题描述】:

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

我尝试在 + 号前使用转义和“%2B”以及反斜杠作为“+”,但到目前为止没有给出任何内容..

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

感谢您的帮助

【问题讨论】:

    标签: javascript


    【解决方案1】:

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

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

    给你:

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

    ...ie 保留 +,这也将在通过 decodeURIComponent() 的反向行程中幸存下来。

    【讨论】:

      【解决方案2】:

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

      如果您或其他人可以更改代码,您可以使用this answer

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

      然后在输入中您希望+ 出现的位置使用空格。

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          【解决方案4】:

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

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

          这更有效,因为它需要一个替换,并且不需要中间“转义”,并且更简单,因为您不必重新实现 encodeURIComponent 并使用本机 可能 em> 对于大字符串会更快。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-06-07
            • 1970-01-01
            • 1970-01-01
            • 2011-11-17
            • 1970-01-01
            • 2012-04-10
            • 2013-09-21
            相关资源
            最近更新 更多