Show search result URL as breadcrumb

1.2k views Asked by At

I need to display the URLs in a list of search results in a breadcrumb style (i.e. such as Google does - Google Breadcrumbs), and have limited knowledge of JavaScript (and haven't touched it in nearly two years). Can you help me please? I can apply the code if it's provided with clear instruction, and am very comfortable with HTML and CSS, but have not attempted to create breadcrumbs without lists before.

Where do I start?

Input would be page's URL (class is .slimBreadcrumbLink) - e.g. https://www.example.com/level1/level2/level3/level4 - and output would be as below:

Level 2 > Level 3 > Level 4

I haven't tried anything of significance yet, I'm starting here. I've read through the other breadcrumb questions posed, but it's not helped so far. I found the below but don't know how to implement it.

var path = location.pathname;

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
  });
}

Thank you.

2

There are 2 answers

2
nicovank On

Here is a function that will create the HTML structure for the breadcrumbs:

const getLevels = url => url.replace(/http(s.):\/\//, "").split("/");
const createBreadcrumb = function(url, elem) {
    const ol = document.createElement("ol");
        getLevels(url).forEach((e, i) => {
            if(i > 2) {
                const li = document.createElement("li");
                const a  = document.createElement("a");

                a.href = url.substring(0, url.indexOf(e) + e.length);
                a.innerText = e;

                li.appendChild(a)        
                ol.appendChild(li);
            }   
        }
    });
    elem.appendChild(ol);
};

Because it is ES6, you will have to use a transpiler like babel to make it compatible with older browsers. Also, because you are parsing the URL, you cannot customize the title of the links.

You can then use the function like this, to parse the url and create the ol list in the element with the id.

createBreadcrumb(url, document.getElementById("id"));
8
gyre On

I rolled my own demo snippet. The code is quite a bit to explain, but if anything doesn't appear self-explanatory feel free to let me know and I'll elaborate more here.

// Utility functions
function createBreadcrumbs (origin, path) {
    var levels = path.slice(1).split('/')
    
    return levels.map(function (e, i, levels) {
      var text = e.replace(/-+/g, ' ').replace(/\s*\b\S/g, function (e) {
          return e.toUpperCase()
      })
      return anchor(origin + '/' + levels.slice(0, i+1).join('/'), text)
    })
}

function anchor (href, text) {
    var a = document.createElement('a')
    a.href = href
    a.textContent = text
    return a
}

function render (breadcrumbs) {
  var ol = document.createElement('ol')
  ol.className = 'breadcrumbs'
  breadcrumbs.forEach(function (anchor) {
      var li = document.createElement('li')
      anchor.className = 'breadcrumbs__link'
      li.className = 'breadcrumbs__crumb'
      li.appendChild(anchor)
      ol.appendChild(li)
  })
  return ol
}


// How to use
var breadcrumbs = createBreadcrumbs('//example.com', '/example-thing/location-stuff/level-2'),
    list = render(breadcrumbs)

console.log(breadcrumbs)
document.body.appendChild(list)
<p>Breadcrumbs for <a href="//example.com/example-thing/location-stuff/level-2">//example.com/example-thing/location-stuff/level-2</a></p>