[Node.js] url-join that nicely combines URLs is convenient
The url-join library for Node.js nicely combines URLs and was convenient, so I’d like to introduce it. By the way, it can also be used in browser JavaScript.
- GitHub: jfromaniello/url-join: Join all arguments together and normalize the resulting url.
- npm: url-join
How to use url-join
I’ll introduce sample code actually using url-join.
My impression after using it is that it’s nice how it properly considers / and URL query parameters ? & to combine URL strings.
Normal case
First, I tried it with a typical pattern. There seems to be no problem.
var urljoin = require('url-join');
urljoin('http://example.com', 'a', '/b/cd', '?foo=123');
// 'http://example.com/a/b/cd?foo=123'
Case with consecutive /
Even in cases like the following where / (slash) appears consecutively, url-join combines them nicely. It’s nice that it trims even if you accidentally have // consecutive.
var urljoin = require('url-join');
urljoin('http://example.com/', '/a', '//b/cd');
// 'http://example.com/a/b/cd'
Case where you want to add multiple URL query parameters
[OK] Just ?
For URL query parameter combination, it seems fine to just add ?.
var urljoin = require('url-join');
urljoin('http://example.com', 'a', '?foo=123', '?bar=456');
// 'http://example.com/a?foo=123&bar=456'
[NG] Just &
As expected, using just & didn’t work. It doesn’t care for this, so let’s use ?.
var urljoin = require('url-join');
urljoin('http://example.com', 'a', '&foo=123', '&bar=456');
// 'http://example.com/a&foo=123&bar=456'
That’s all from the Gemba that wants to combine URL parameters without worrying about details.