Javascript Location Get protocol and host name

Description

Javascript Location Get protocol and host name

View in separate window

<!DOCTYPE html>
<html>
<head>
<title>breadcrumb trail</title>
<script>
window.onload=function() {//from w ww. j ava  2  s.  com
  // split relative path
  let items = location.pathname.substr(1).split("/");

  // build main path
  let mainpath = "<a href='" + location.protocol + "//" + location.hostname + "/";

  // begin breadcrumb
  let breadcrumbTrail = "<p>";
  for (let i = 0; i < items.length; i++) {

    // trailing slash
    if (items[i].length == 0 ) break;

    // extend main path for new level
    mainpath+=items[i];

    // add slash after all but last item
    if (i < items.length-1)
      mainpath+="/";

    // create breadcrumb component
    // add arrows for interior items only
    if (i > 0 && i < items.length)
      breadcrumbTrail+=" -> ";

    // add crumb
    breadcrumbTrail+= mainpath + "'>" + items[i] + "</a>";
  }

  // insert into page
  breadcrumbTrail+="</p>";
  document.getElementById("breadcrumb").innerHTML=breadcrumbTrail;

}

</script>
</head>
<body>
<div id="breadcrumb"></div>
</body>
</html>



PreviousNext

Related