Spacing between words ruins URL?

Viewed 534
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);
};

Hey guys, above is the command, it works though, when attempting to add several words, i-e. "hello world it catches only the hello, after putting a space it breaks. I'm not entirely sure how to allow spaces.

Any help is appreciated.

Example -

Example Image

5 Answers

As space is unsafe character use encodeURIComponent for url encoding

URL Encoding converts reserved, unsafe, and non-ASCII characters in URLs to a format that is universally accepted and understood by all web browsers and servers

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

You can use the %20 that represents a space.

I don't know the programming language you are using, but encoding the URL might be helpful. Here's an example in Python:

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

So encode_url('Hello World!') would return '%48%65%6c%6c%6f%20%57%6f%72%6c%64%21' which is accepted in URLs.

Related