Extract URL's directory from path, without file name such as “index.html”

后端 未结 2 513
执念已碎
执念已碎 2021-01-14 06:16

I am looking for plain JavaScript code (no jQuery etc.) to learn the directory path component of my currently loaded page\'s URL.

For instance, if my page is loaded

2条回答
  •  爱一瞬间的悲伤
    2021-01-14 06:47

    It looks like this does the trick:

    var href = window.location.href;
    var dir = href.substring(0, href.lastIndexOf('/')) + "/";
    

    Is this a safe method or can this fail with more complex URLs?

提交回复
热议问题