Last active
November 2, 2024 11:56
-
-
Save dillonstreator/5b06d04d955d6f1d9b796db9aa7994d4 to your computer and use it in GitHub Desktop.
Javascript generate breadcrumb array from url pathname
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const titleizeWord = (str) => `${str[0].toUpperCase()}${str.slice(1)}`; | |
const kebabToTitle = (str) => str.split("-").map(titleizeWord).join(" "); | |
const toBreadcrumbs = (pathname, { rootName = "Home", nameTransform = s=>s } = {}) => | |
pathname | |
.split("/") | |
.filter(Boolean) | |
.reduce( | |
(acc, curr, idx, arr) => { | |
acc.path += `/${curr}`; | |
acc.crumbs.push({ | |
path: acc.path, | |
name: nameTransform(curr), | |
}); | |
if (idx === arr.length - 1) return acc.crumbs; | |
else return acc; | |
}, | |
{ path: "", crumbs: [{ path: "/", name: rootName }] }, | |
); | |
toBreadcrumbs("/team-members/joe-schmoe", { nameTransform: kebabToTitle }); | |
/* | |
[ | |
{ path: "/", name: "Home" }, | |
{ path: "/team-members", name: "Team Members }, | |
{ path: "/team-members/joe-schmoe", name: "Joe Schmoe" }, | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment