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

后端 未结 16 1321
甜味超标
甜味超标 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';
            }
        }); 
    });
    

提交回复
热议问题