I recently found myself needing to URL encode a string, in Node – to convert a space into %20 in this case, but also to handle other scenarios.
My initial thought was “oh, great – I’ll need to find a library that doesn’t completely suck”.
Turns out I didn’t need to find anything. JavaScript has a built-in function to handle this: encodeURI
Pass any string to it, and it will produce the correctly encoded string as output:
There is a decodeURI method as well, to take an encoded string and produce a decoded version:
These methods have been in JavaScript since EMCAScript 3, I just never knew about them until a few days ago.
The next time you need to encode or decode a URL or other URI string, then, you can do so with JavaScript’s built-in functions.