can this be further simplified

i have run into an issue in an astro template and am gonna make a pr with the fix. but the current solution feels hacky
const { href, class: className, ...props } = Astro.props;
let pathnameWithoutSlash = Astro.url.pathname.replace(/\/$/, "");

if (href === "/" && pathnameWithoutSlash === "") {
pathnameWithoutSlash = "/";
}

const isActive = href === pathnameWithoutSlash;
const { href, class: className, ...props } = Astro.props;
let pathnameWithoutSlash = Astro.url.pathname.replace(/\/$/, "");

if (href === "/" && pathnameWithoutSlash === "") {
pathnameWithoutSlash = "/";
}

const isActive = href === pathnameWithoutSlash;
can this be simplified somehow? should i just make a pr and let the maintainers review it?
58 Replies
John
John2y ago
Excuse me but why are you first removing the slash and then adding it back
Halu
Halu2y ago
cuz u only add it back if href==="/" you could check b4 removing w/ turnary ig
nexxel
nexxel2y ago
okay so Astro.url.pathname returns "/" for home and "/blog/" for blog and href is only "/blog" so they don't match and it doesn't become acting so i have to remove the trailing slash but then in home "/" becomes "" so i have to add it back just for home
John
John2y ago
I’d test with RegEx if the pathname only contains slash and if not is just trimEnd
nexxel
nexxel2y ago
should you really put complex regex in a template tho? astro is really aimed at beginners i think we should keep it as simple as possible
John
John2y ago
Gonna think, brb I’m a minute
Halu
Halu2y ago
let pathname = Astro.url.pathname || '/'
if ( href === "/" && '/' !== pathname) pathname = pathname.replace(/\/$/, "")
let isActive = href === pathname
let pathname = Astro.url.pathname || '/'
if ( href === "/" && '/' !== pathname) pathname = pathname.replace(/\/$/, "")
let isActive = href === pathname
John
John2y ago
John
John2y ago
nexxel is this the use you are looking for?
let result = pathname
const pathIsBlank = pathname.match(/^\/$/);
if (!pathIsBlank) {
result = pathname.slice(0, -1);
}
let result = pathname
const pathIsBlank = pathname.match(/^\/$/);
if (!pathIsBlank) {
result = pathname.slice(0, -1);
}
or
const result = pathname.match(/^\/$/) ? pathname : pathname.slice(0,-1);
const result = pathname.match(/^\/$/) ? pathname : pathname.slice(0,-1);
tho ^ and $ might need to be replaced with \A and \z
nexxel
nexxel2y ago
lemme try both of these this doesn't seem to work :(
Halu
Halu2y ago
i didnt try it myself lol oh, cuz i didnt reassign after replace maybe
John
John2y ago
coz astro.url.pathname is always truthy
Halu
Halu2y ago
""
John
John2y ago
|| compares the length of strings. isnt pathname for home is '/' ?
Halu
Halu2y ago
wasnt going to assume
Want results from more Discord servers?
Add your server