Get parent path of URL


You want to know the path of the parent directory so that you can easily create an absolute path on your detail page? You can simply use ".." and the browser will take care of it, but if you're using a single page application router you'll often have to determine the path yourself.

Your page is this /top-directory/category/product-1.html

And you want to get this: /top-directory/category/

Or maybe your page is this: /top-directory/category/product-1/

Either way, the script below will get your the path up to category!


var input = '/top-directory/category/product-1.html'
var directory  = input.replace(/[^/]+[/]{0,1}$/, '')


Please sign-in to post a comment