The regex for checking a path is relative or absolute

I track the onclick event in the "a" tag, the onclick function will get the href attr of the "a" tag. I want to check that href is an absolute path or relative path. is there a regex expression to test this.

and other than this template

"/myfolder/test.txt" "http://example.com" "https://example.com" 

which are another template that I have to check.

+5
source share
5 answers

If you want to check all anchor tags, you can do this. Checking RegEx checks for typos AKA fat fingers.

 function checkRelpath(){ var anChrs = $('a'); $.each(anChrs, function(idx, itm){ var pattern = new RegExp('/^(http|https|http:|https:|\/\/)/'), path = $(itm).prop('href'), testPath = pattern.test(path); console.log(path); console.log(testPath); }); } 

Or, if you want to test a specific anchor, you can do it.

 function checkThisRelpath(a){ var pattern = new RegExp('/^(http|https|http:|https:|\/\/)/'), path = $(a).prop('href'), testPath = pattern.test(path); console.log(path); console.log(testPath); } 
+1
source

Here is a solution using URI.js # is :

 function isAbsoluteUri(str) { var uri = new URI(str); return uri.is('absolute'); } console.log(isAbsoluteUri('/myfolder/test.txt')); console.log(isAbsoluteUri('~/myfolder/test.txt')); console.log(isAbsoluteUri('?hello=world')); console.log(isAbsoluteUri('http://example.com')); console.log(isAbsoluteUri('https://example.com')); console.log(isAbsoluteUri('ftp://example.com')); console.log(isAbsoluteUri('mailto: mail@example.com ')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.2/URI.min.js"></script> 
+7
source

Why are you worried about regex? Use str.startsWith :

 console.log("/myfolder/test.txt".startsWith("/")); console.log("http://example.com".startsWith("/")); console.log("https://example.com".startsWith("/")); 

If you need to consider the case of paths starting with / or ~ :

 console.log(/^([?/~]|mailto.*@.*\.\w+$)/.test("mailto: mail@example.org ")); console.log(/^([?/~]|mailto.*@.*\.\w+$)/.test("~/myfolder/test.txt")); console.log(/^([?/~]|mailto.*@.*\.\w+$)/.test("/myfolder/test.txt")); console.log(/^([?/~]|mailto.*@.*\.\w+$)/.test("http://example.com")); console.log(/^([?/~]|mailto.*@.*\.\w+$)/.test("https://example.com")); 
+6
source

If you know that you always get the right path, then you really need to check if it starts with / . This should do it:

 ^\/.* 

Example: https://regex101.com/r/rdox2A/1

+3
source
 /** * Return true is the URL is absolute * * @export * @param {string} url * @returns */ export function isURLAbsolute(url) { if (typeof url !== 'string') { throw new TypeError('Expected a string'); } return /^[az][a-z0-9+.-]*:/.test(url); } 
-1
source

Source: https://habr.com/ru/post/1258450/


All Articles