Convert relative path to absolute using JavaScript

后端 未结 11 1571
误落风尘
误落风尘 2020-11-28 05:15

There\'s a function, which gives me urls like:

./some.css
./extra/some.css
../../lib/slider/slider.css

It\'s always a relative path.

<
11条回答
  •  猫巷女王i
    2020-11-28 05:31

    I found a very simple solution to do this while still supporting IE 10 (IE doesn't support the URL-API) by using the History API (IE 10 or higher). This solution works without any string manipulation.

    function resolveUrl(relativePath) {
        var originalUrl = document.location.href;
        history.replaceState(history.state, '', relativePath);
        var resolvedUrl = document.location.href;
        history.replaceState(history.state, '', originalUrl);
        return resolvedUrl;
    }
    

    history.replaceState() won't trigger browser navigation, but will still modify document.location and supports relative aswell as absolute paths.

    The one drawback of this solution is that if you are already using the History-API and have set a custom state with a title, the current state's title is lost.

提交回复
热议问题