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

后端 未结 16 1315
甜味超标
甜味超标 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:39

    It should not start with a slash or hash, and it should not contain a double slash if not preceded by question mark or hash? I would not test that with a single regexp, it would be very complicated to match "no double slash".

    function test(s) {
        return s.charAt(0) != "#"
          && s.charAt(0) != "/"
          && ( s.indexOf("//") == -1 
            || s.indexOf("//") > s.indexOf("#")
            || s.indexOf("//") > s.indexOf("?")
        );
    }
    

    would be easier, clearer and imho faster.

提交回复
热议问题