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

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

    You can use a try, catch block to help with this. Rather than using a regular expression, you can use the URL interface at every step.

    isExternalUrl (urlString) {
      try {
        const url = new URL(urlString) // THROW ON MISSING SCHEME
    
        // DOES THIS URL ORIGINATE FROM THIS WEBSITE?
        if (url.origin !== new URL(document.URL, document.baseURI).origin) {
          return true // IS EXTERNAL URL
        }
      } catch (_e) {
        // THROWS WHEN URL DOES NOT HAVE A SCHEME
        new URL(urlString, document.baseURL) // THROW AN EXCEPTION IF THE URL IS TRULY MALFORMED IN SOME WAY
      }
    
      return false
    }
    

提交回复
热议问题