How to make strings URI/URL friendly in Node.js/JavaScript?

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.

I thought that I need some external library to do that, but I was wrong! JavaScript has a built-in function to solve my problem – encodeURI.

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"

This works in Node also, and it is not a new thing. It was part od JavaScript since ECMAScript 3!

Published by Stjepan

Just another software developer

Leave a comment

Your email address will not be published. Required fields are marked *