Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 224
TruMan1 Avatar asked May 21 '12 14:05

TruMan1


People also ask

How do you know if a URL is absolute or relative in Python?

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.

Is URL absolute?

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.

Is URL relative?

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.

Can links be absolute and relative?

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.


2 Answers

FAST

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) 

UNIVERSAL

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 

Explain the RegExp

^(?:[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

like image 165
Geo Avatar answered Sep 28 '22 07:09

Geo


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

For protocol relative urls, use this regex:

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

like image 22
strah Avatar answered Sep 28 '22 07:09

strah