how to get the base url in javascript

前端 未结 10 1858
一整个雨季
一整个雨季 2020-12-01 04:12

I am building a website with CodeIgniter, I have various resources that I load with the base_url helper function like this

10条回答
  •  难免孤独
    2020-12-01 04:38

    Base URL in JavaScript

    You can access the current url quite easily in JavaScript with window.location

    You have access to the segments of that URL via this locations object. For example:

    // This article:
    // https://stackoverflow.com/questions/21246818/how-to-get-the-base-url-in-javascript
    
    var base_url = window.location.origin;
    // "http://stackoverflow.com"
    
    var host = window.location.host;
    // stackoverflow.com
    
    var pathArray = window.location.pathname.split( '/' );
    // ["", "questions", "21246818", "how-to-get-the-base-url-in-javascript"]
    

    In Chrome Dev Tools, you can simply enter window.location in your console and it will return all of the available properties.


    Further reading is available on this Stack Overflow thread

提交回复
热议问题