Skip to content

Instantly share code, notes, and snippets.

@yurkimus
Created July 14, 2024 13:29
Show Gist options
  • Save yurkimus/ec488626b7d74d23d95efa347a2f23ca to your computer and use it in GitHub Desktop.
Save yurkimus/ec488626b7d74d23d95efa347a2f23ca to your computer and use it in GitHub Desktop.
URLPathname
let pathname = new URLPathname({
pathname: '/user/:user/todos/:todo',
search: 'tab=aaa',
hash: 'section',
});
pathname.toString([
['user', 1],
['todo', 1],
]) // => /user/1/todos/1?tab=aaa#section
pathname.toString() // => user/:user/todos/:todo/tab=aaa#section
new URL(pathname, 'http://example.org')
new URL(
pathname.toString([
['user', 1],
['todo', 1],
]),
'http://example.org'
)
function URLPathname(...parameters) {
this.pathname = parameters.at(0).pathname;
this.searchParams = new URLSearchParams(parameters.at(0).searchParams);
this.hash = parameters.at(0).hash;
}
URLPathname.prototype.toString = function (properties) {
var pathname = this.pathname;
switch (Object.prototype.toString.call(properties)) {
case '[object Array]':
for (var property of properties)
pathname = pathname.replace(':' + property.at(0), property.at(1));
break;
case '[object Object]':
for (var property in properties)
pathname = pathname.replace(':' + property, properties[property]);
break;
}
if (pathname) {
if (this.searchParams.size && this.hash) {
return pathname + '?' + this.searchParams + '#' + this.hash;
} else if (this.searchParams.size) {
return pathname + '?' + this.searchParams;
} else if (this.hash) {
return pathname + '#' + this.hash;
} else {
return pathname;
}
}
};
URLPathname.prototype[Symbol.toPrimitive] = function (hint) {
switch (hint) {
case 'string':
case 'default':
return this.toString();
default:
return null;
}
};
URLPathname.of = (...parameters) => new URLPathname(...parameters);
URLPathname[Symbol.toStringTag] = 'URLTemplate';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment