Imaginebeingme
Imaginebeingme

Reputation: 175

Spacing between words ruins URL?

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

Upvotes: 2

Views: 1085

Answers (5)

gkucmierz
gkucmierz

Reputation: 1145

encodeURIComponent them!

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

Upvotes: 0

saketh
saketh

Reputation: 813

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)}`;

Upvotes: 3

Pranav
Pranav

Reputation: 491

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.

Upvotes: 0

Rounin
Rounin

Reputation: 29511

Special characters in URLs are encoded using a format called percent-encoding.

A space is represented by %20.

e.g. https://example.com/hello%20world/


Further Reading:

Upvotes: 0

Daniel Garc&#237;a
Daniel Garc&#237;a

Reputation: 46

You can use the %20 that represents a space.

Upvotes: 1

Related Questions