【问题标题】:Spacing between words ruins URL?单词之间的间距会破坏 URL?
【发布时间】:2020-11-03 06:24:51
【问题描述】:
exports.exec = async (client, message, args) => {
    // Fires Error message that the command wasn't ran correctly.
    if (args.length < 1) {
        return message.channel.send({
            embed: {
                color: 0,
                description: `${message.author} Please input something to be generated into the QR code.`
            }
        });
    }
    // Fires Error message that the command wasn't ran correctly.

    var text = args.join(' ');
    var qr_generator = `https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${text}`;
    message.channel.send(qr_generator);
};

大家好,上面是命令,但它工作,当尝试添加几个单词时,即。 "hello world 它只捕获 hello,在放置一个空格后它会中断。我不完全确定如何允许空格。

感谢任何帮助。

例子-

【问题讨论】:

标签: javascript discord discord.js


【解决方案1】:

由于空格是不安全的字符 使用encodeURIComponent进行url编码

URL 编码将 URL 中的保留、不安全和非 ASCII 字符转换为所有 Web 浏览器和服务器普遍接受和理解的格式

 var qr_generator = `https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(text)}`;

【讨论】:

    【解决方案2】:

    您可以使用代表空格的%20

    【讨论】:

      【解决方案3】:

      URL 中的特殊字符使用称为 percent-encoding 的格式进行编码。

      空格由%20表示。

      例如 https://example.com/hello%20world/


      进一步阅读:

      【讨论】:

        【解决方案4】:

        我不知道您使用的编程语言,但对 URL 进行编码可能会有所帮助。下面是一个 Python 示例:

        def encode_url(url):
            encoded = ''
            for special_char in url:
                encoded += '%' + hex(ord(special_char)).lstrip('0x')
            return encoded
        

        所以encode_url('Hello World!') 会返回'%48%65%6c%6c%6f%20%57%6f%72%6c%64%21',这在 URL 中是可以接受的。

        【讨论】:

          【解决方案5】:

          encodeURIComponent他们!

          console.log( encodeURIComponent('hello world!') );

          【讨论】:

          猜你喜欢
          • 2011-01-14
          • 2018-09-15
          • 1970-01-01
          • 1970-01-01
          • 2014-06-16
          • 2015-10-03
          • 1970-01-01
          • 1970-01-01
          • 2011-09-30
          相关资源
          最近更新 更多