I had to use external API for sending SMS in Node and to get it to work I needed to send GET request with the message as a query parameter in URL.
You can’t use URL if there are spaces in it, so I needed to URL encode my message first.
This is how it works. You pass any string to it, and it will return correctly encoded string as output:
const output = encodeURI("http://sms.com/api/send?message=I have spaces"); console.log(output); // <= "http://sms.com/api/send?message=I%20have%20spaces"
encodeURI escapes all characters except: A-Z a-z 0-9 ; , / ? : @ & = + $ – _ . ! ~ * ‘ ( ) #
It is important to know that encodeURI by itself cannot form proper HTTP GET and POST requests, because “&”, “+”, and “=” are not encoded, which are treated as special characters in GET and POST requests. If you need to encode this characters use encodeURIComponent.
If you need to decode URL, there is also built-in function for that – decodeURI. Here is how it works:
const input = decodeURI("http://sms.com/api/send?message=I%20have%20spaces"); console.log(input); // <= "http://sms.com/api/send?message=I have spaces"