Skip to content Skip to sidebar Skip to footer

Javascript Url Depth (level)

Is it possible to get url depth (level) with Javascript? If I have this url: www.website.com/site/product/category/item -> depth=4 www.website.com/site/product/category -> de

Solution 1:

I would use a regex to determine how many matches there are for a slash followed by one or more characters.

var url = "www.website.com/site/product/category/item";
url.match(/\/.+?/g).length; // returns 4

Edit: Added a few checks against query strings and double slashes. (credit to user Lix for sparking the idea)

var url = "www.website.com/site/product/category/item?url=/query/string/path";
url.split(/[?#]/).shift().match(/\/[^/]+?/g).length;

Solution 2:

simply split it by "/" and check the length of returning array

var url = "www.website.com/site/product/category/item";
    alert("depth is " + (url.split("/").length - 1));
    url = "www.website.com/site/product/category"alert("depth is " + (url.split("/").length - 1));

Post a Comment for "Javascript Url Depth (level)"