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
Python 2. You can use the urlparse module to parse an URL and then you can check if it's relative or absolute by checking whether it has the host name set.
What are Absolute URLs? An absolute URL contains the entire address from the protocol (HTTPS) to the domain name (www.example.com) and includes the location within your website in your folder system (/foldernameA or /foldernameB) names within the URL. Basically, it's the full URL of the page that you link to.
A relative URL is a URL that only includes the path. The path is everything that comes after the domain, including the directory and slug. Because relative URLs don't include the entire URL structure, it is assumed that when linking a relative URL, it uses the same protocol, subdomain and domain as the page it's on.
There are two types of links you can use to direct search engine bots to your web page: absolute links and relative links. An absolute link provides the complete location information of your site, while a relative link only contains the location following your domain.
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)
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
^(?:[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
var pat = /^https?:\/\//i; if (pat.test(urlString)) { //do stuff }
For protocol relative urls, use this regex:
/^https?:\/\/|^\/\//i
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With