Evanss
Evanss

Reputation: 23612

jQuery generate breadcrumbs from url?

Is there a way of getting jQuery to generate breadcrumbs on a page from the url?

So if the site url was: mysite.com/sec1/sec2/page

The breadcrumbs would be something like: Home > Sec1 > Sec2 > Page

Thanks

Upvotes: 6

Views: 9634

Answers (6)

dillon
dillon

Reputation: 733

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" },
]
*/

Upvotes: 0

C.Wainaina
C.Wainaina

Reputation: 81

Full Javascript function to display breadcrumbs from page url based on Bill Criswell's answer

  function getBreadcrumbs() {
    const here = location.href.split('/').slice(3);
    // console.log(here)
    const parts = [{"text": 'Home', "link": '/'}];
    // console.log(parts)

    for (let i = 0; i < here.length; i++) {
        const part = here[i];
        // console.log(part)
        const text = decodeURIComponent(part).toUpperCase().split('.')[0];
        // console.log(text)
        const link = '/' + here.slice(0, i + 1).join('/');
        console.log(link)
        parts.push({"text": text, "link": link});
        // console.log(parts)
    }
    return parts.map((part) => {
        return "<a href=\"" + part.link + "\">" + part.text + "</a>"
    }).join('<span style="padding: 5px">/</span>')
}

document.getElementById("demo").innerHTML = getBreadcrumbs();

Upvotes: 3

Bill Criswell
Bill Criswell

Reputation: 32921

This will create an array you can use to generate breadcrumbs.

var here = location.href.split('/').slice(3);

var parts = [{ "text": 'Home', "link": '/' }];

for( var i = 0; i < here.length; i++ ) {
    var part = here[i];
    var text = part.toUpperCase();
    var link = '/' + here.slice( 0, i + 1 ).join('/');
    parts.push({ "text": text, "link": link });
}

Though, I really think you should be handling this at the server side!

Upvotes: 3

Chris Pratt
Chris Pratt

Reputation: 239400

jQuery doesn't have any unique URL parsing abilities aside from what JavaScript itself provides. You can get the URL path with:

var path = location.pathname;

Then, you can get the parts of the path with:

var parts = path.split('/');

Then, just loop through the parts and generate your breadcrumb HTML as you see fit.

Upvotes: 0

Jose Faeti
Jose Faeti

Reputation: 12304

splitted_url = document.url.split('/');

Will give you an array containing each directory, then you can access them like splitted_url[0]

Upvotes: 0

Sjoerd
Sjoerd

Reputation: 75629

var url = 'mysite.com/sec1/sec2/page'; // = location.href
var parts = url.split('/');
parts[0] = 'Home';
var breadcrumb = parts.join(' &gt; ');
$('#breadcrumb').html(breadcrumb);

Upvotes: 2

Related Questions