Created
January 12, 2021 16:08
-
-
Save adrielTosi/cddcfbbf820ab3f46914d1b31d6268c4 to your computer and use it in GitHub Desktop.
Make path into crumbs - array of objects with title and link
This file contains 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
/** | |
* Generate breadcrumb based on the path given | |
* Taken/adapted from here https://github.com/intesso/url-breadcrumb/blob/master/index.js | |
*/ | |
const generateCrumbsFromPath = (url, opts) => { | |
// options | |
opts = opts || {}; | |
opts.home = opts.home || "Home"; | |
opts.endingSlash = opts.endingSlash || false; | |
opts.beautify = | |
opts.beautify || | |
function(str) { | |
// Take off -, _ and make every first letter capitalized | |
return str | |
.replace(/[-_]/g, " ") | |
.replace(/\w\S*/g, (w) => w.replace(/^\w/, (c) => c.toUpperCase())); | |
}; | |
// extract url path (without querystring and without hash) | |
const urlPath = url.split(/[?#]/)[0]; | |
// split segments by slash and filter empty elements | |
const segments = urlPath.split("/").filter(Boolean); | |
// add first element for `home` element | |
segments.unshift(""); | |
// enhance segments array | |
return segments.map((crumb, i, arr) => { | |
// join the segments array up to the actual element with slash | |
var p = arr.slice(0, i + 1).join("/"); | |
if (opts.endingSlash) { | |
// the last element must get the ending slash back, if it was there originally (lost during split) | |
// every higher path segment must get an ending slash. | |
if (i < arr.length - 1 || urlPath.endsWith("/")) p += "/"; | |
} else { | |
// the first element must always be a slash | |
if (i === 0) p = "/"; | |
} | |
// the first element must get the `home` name, every other element must be uri decoded | |
crumb = i === 0 ? opts.home : decodeURIComponent(crumb); | |
return { | |
name: crumb, | |
title: opts.beautify(crumb), | |
link: segments.length - 1 === i ? null : p, | |
}; | |
}); | |
}; | |
export default generateCrumbsFromPath; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment