【问题标题】:Javascript replace query string + with a spaceJavascript用空格替换查询字符串+
【发布时间】:2023-03-27 06:00:01
【问题描述】:

我正在获取查询字符串参数并尝试这样做:

var hello = unescape(helloQueryString); 

然后它返回:

this+is+the+string

代替:

this is the string

如果 %20 在那里,效果很好,但它是 +。有什么方法可以正确解码这些,使它们 + 符号变为空格?

谢谢。

【问题讨论】:

    标签: javascript url query-string decode


    【解决方案1】:

    之后添加这一行会起作用:

    hello = hello.replace( '+', ' ' );
    

    【讨论】:

    • hello = hello.replace(/\+/g, ' ') 如果您预计单词之间会有更多空格。
    • 这样做不是更好吗(这样你就不会出现巨大的空格间隙):hello.replace(/\++/, '')
    【解决方案2】:

    decodeURIComponent 函数将正确处理解码:

    decodeURIComponent("this%20is%20the%20string"); // "this is the string"
    

    请看以下文章:

    【讨论】:

    • 问题是专门询问带有 + 而不是 %20 的字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2020-12-19
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    相关资源
    最近更新 更多