[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.
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.
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'
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'
[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.