How to test if a URL string is absolute or relative?

后端 未结 16 1302
甜味超标
甜味超标 2020-11-29 20:05

How can I test a URL if it is a relative or absolute path in Javascript or jQuery? I want to handle accordingly depending if the passed in URL is a local or external path.

相关标签:
16条回答
  • 2020-11-29 20:53

    Following function will get called when click event occurs on a hyperlink i.e 'a' tag if the tag contains url will be relative or contains same host then that new page will get loaded into same browser tab, If it contains different url then page will load in new browser tab

    jQuery(document).ready(function() {
        $('a').click(function(){
    
            var a = this;
            var a_href = $(this).attr('href');
            var regex = new RegExp('^(?:[a-z]+:)?//', 'i');     
    
            if(a.host == location.host || regex.test(a_href) == false){
                a.target = '_self';
            }else{
                a.target = '_blank';
            }
        }); 
    });
    
    0 讨论(0)
  • 2020-11-29 20:57
    var isExternalURL = url.toLowerCase().indexOf('http://') === 0 || url.toLowerCase().indexOf('https://') === 0 ;
    
    0 讨论(0)
  • 2020-11-29 20:59

    Use a regex:

    if (/^(?:[a-z]+:)?\/\//i.test(url))
    
    0 讨论(0)
  • 2020-11-29 21:02

    FAST

    If you only need to test for http:// or https:// then the most efficient way is:

    if (urlString.indexOf('http://') === 0 || urlString.indexOf('https://') === 0)
    

    UNIVERSAL

    However, I would suggest a more universal, non case-sensitive, protocol-agnostic approach:

    var r = new RegExp('^(?:[a-z]+:)?//', 'i');
    r.test('http://example.com'); // true - regular http absolute URL
    r.test('HTTP://EXAMPLE.COM'); // true - HTTP upper-case absolute URL
    r.test('https://www.exmaple.com'); // true - secure http absolute URL
    r.test('ftp://example.com/file.txt'); // true - file transfer absolute URL
    r.test('//cdn.example.com/lib.js'); // true - protocol-relative absolute URL
    r.test('/myfolder/test.txt'); // false - relative URL
    r.test('test'); // false - also relative URL
    

    Explain the RegExp

    ^(?:[a-z]+:)?//
    

    ^ - beginning of the string
    (?: - beginning of a non-captured group
    [a-z]+ - any character of 'a' to 'z' 1 or more times
    : - string (colon character)
    )? - end of the non-captured group. Group appearing 0 or 1 times
    // - string (two forward slash characters)
    'i' - non case-sensitive flag

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