【问题标题】:javascript encodeURIComponent and converting spaces to + symbolsjavascript encodeURIComponent 并将空格转换为 + 符号
【发布时间】:2012-06-07 03:01:57
【问题描述】:

我想对我的 URL 进行编码,但我想将空格转换为加号。

这就是我试图做的......

var search = "Testing this here &";

encodeURIComponent(search.replace(/ /gi,"+"));

它的输出是Testing%2Bthis%2Bhere%2B%26,但我希望它是Testing+this+here+%26 我尝试用%20 替换空格以将其转换为加号,但这似乎不起作用。谁能告诉我我在这里做错了什么?

【问题讨论】:

    标签: javascript regex replace encodeuricomponent


    【解决方案1】:
    encodeURIComponent(search).replace(/%20/g, "+");
    

    你在这里做错的是首先你将空格转换为加号,然后encodeURIComponent将加号转换为"%2B"

    【讨论】:

    • 如果字符串包含任何“真实的”+ 字符会导致问题。
    • @user1419007 不,不会。所有“原始”加号都转换为"%2B" 并由replace 保存。
    • 啊,我真傻,谢谢。 8 分钟结束后,我会为你选出最佳答案。
    • @user1419007 我一开始放的是 %2B 而不是 %20。立即更正。
    • 这可能会破坏多字节字符编码。
    【解决方案2】:

    自己试试encodeURI()encodeURIComponent()...

    console.log(encodeURIComponent('@#$%^&*'));

    输入:@#$%^&*。输出:%40%23%24%25%5E%26*。那么,等等,* 发生了什么?为什么没有转换? TLDR:您实际上想要fixedEncodeURIComponent()fixedEncodeURI()。长篇大论...

    不要直接使用encodeURIComponent()

    您应该使用 fixedEncodeURIComponent(),如 MDN 文档所示。 encodeURIComponent 不编码以下任何内容:!',()*。您需要使用此其他功能。它不仅可以解决您的空间问题,还可以解决其他性格问题。

    function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }

    引用 MDN 文档encodeURIComponent()...

    为了更严格地遵守 RFC 3986(保留 !、'、(、) 和 *),即使这些字符没有正式的 URI 分隔用途,也可以安全地使用以下字符:fixedEncodeURIComponent()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 2011-12-13
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      相关资源
      最近更新 更多