Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/utils/__tests__/url.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { strict as assert } from 'node:assert';
import { describe, it } from 'node:test';

import { relative } from '../url.mjs';

describe('url util', () => {
describe('relative()', () => {
it('returns the same URL if it includes a protocol', () => {
assert.equal(
relative('https://example.com', '/foo/bar'),
'https://example.com'
);
assert.equal(
relative('http://nodejs.org', '/foo/bar'),
'http://nodejs.org'
);
});

it('returns the same URL if it starts with a hash fragment', () => {
assert.equal(relative('#fragment', '/foo/index.html'), '#fragment');
});

it('returns the same URL if it starts with a query string', () => {
assert.equal(relative('?query=true', '/foo/index.html'), '?query=true');
});

it('returns the relative path between two URLs', () => {
assert.equal(relative('/api/fs.html', '/api/crypto.html'), 'fs.html');
assert.equal(
relative('/api/fs.html#slug', '/api/fs.html'),
'fs.html#slug'
);
assert.equal(
relative('/foo/bar.html', '/baz/qux.html'),
'../foo/bar.html'
);
assert.equal(
relative('/foo/bar.html', '/foo/bar/baz.html'),
'../bar.html'
);
assert.equal(relative('/a/b/c.html', '/x/y/z.html'), '../../a/b/c.html');
});
});
});
4 changes: 4 additions & 0 deletions src/utils/url.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ export const relative = (to, from) => {
return to;
}

if (to.startsWith('#') || to.startsWith('?')) {
return to;
}

const a = to.split('/').filter(Boolean);
const b = from.split('/').slice(0, -1).filter(Boolean);

Expand Down
Loading