javascriptjquerystringurl

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


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.

if (urlString starts with http:// or https://)
 //do this

Solution

  • var pat = /^https?:\/\//i;
    if (pat.test(urlString))
    {
        //do stuff
    }
    

    For protocol relative urls, use this regex:

    /^https?:\/\/|^\/\//i