Convert relative path to absolute using JavaScript

后端 未结 11 1570
误落风尘
误落风尘 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条回答
  •  忘掉有多难
    2020-11-28 05:20

    If you want to make a relative-to-absolute conversion for a link from a custom webpage in your browser (not for the page that runs your script), you can use a more enhanced version of the function suggested by @Bergi:

    var resolveURL=function resolve(url, base){
        if('string'!==typeof url || !url){
            return null; // wrong or empty url
        }
        else if(url.match(/^[a-z]+\:\/\//i)){ 
            return url; // url is absolute already 
        }
        else if(url.match(/^\/\//)){ 
            return 'http:'+url; // url is absolute already 
        }
        else if(url.match(/^[a-z]+\:/i)){ 
            return url; // data URI, mailto:, tel:, etc.
        }
        else if('string'!==typeof base){
            var a=document.createElement('a'); 
            a.href=url; // try to resolve url without base  
            if(!a.pathname){ 
                return null; // url not valid 
            }
            return 'http://'+url;
        }
        else{ 
            base=resolve(base); // check base
            if(base===null){
                return null; // wrong base
            }
        }
        var a=document.createElement('a'); 
        a.href=base;
    
        if(url[0]==='/'){ 
            base=[]; // rooted path
        }
        else{ 
            base=a.pathname.split('/'); // relative path
            base.pop(); 
        }
        url=url.split('/');
        for(var i=0; i

    It'll return null if something is wrong.

    Usage:

    resolveURL('./some.css', 'http://example.com/stats/2012/'); 
    // returns http://example.com/stats/2012/some.css
    
    resolveURL('extra/some.css', 'http://example.com/stats/2012/');
    // returns http://example.com/stats/2012/extra/some.css
    
    resolveURL('../../lib/slider/slider.css', 'http://example.com/stats/2012/');
    // returns http://example.com/lib/slider/slider.css
    
    resolveURL('/rootFolder/some.css', 'https://example.com/stats/2012/');
    // returns https://example.com/rootFolder/some.css
    
    resolveURL('localhost');
    // returns http://localhost
    
    resolveURL('../non_existing_file', 'example.com')
    // returns null
    

提交回复
热议问题