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

后端 未结 2 510
执念已碎
执念已碎 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?

    0 讨论(0)
  • 2021-01-14 06:53

    Highlighting the comment in the question that helped me:

    Phylogenesis's comment:

    The simple solution is location.href.replace(/[^/]*$/, ''); then.

    0 讨论(0)
提交回复
热议问题