Created
May 13, 2015 23:54
-
-
Save trevorhreed/2ee05cc94e67a2675e47 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isRelative(url){ | |
if (/^(((file:|https?:)?\/\/?)?[a-z0-9][a-z0-9-]*(\.([a-z0-9-]*[a-z0-9]))+(:\d+)?|((file:|https?:)?\/\/\/?[a-z0-9][a-z0-9-]*(\.([a-z0-9-]*[a-z0-9]))*))+(:\d+)?/i.test(url)) return false; | |
return true; | |
if(!url) return true; | |
if(/^\/\/[^\/]+\.[^\/]/.test(url)) return false; | |
if(/^\/\/\/[^\/]+/.test(url)) return false; | |
if(/^https?:\/\//.test(url)) return false; | |
var dot = url.indexOf('.'), | |
slash = url.indexOf('/'); | |
if(dot > -1 && ( dot < slash || slash == -1)) return false; | |
return true; | |
} | |
var testData = [ | |
{relative: true,url: "/path/to/file.ext"}, | |
{relative: true,url: "path/to/file.ext"}, | |
{relative: true,url: "file"}, | |
{relative: true,url: "/path"}, | |
{relative: true,url: "#target"}, | |
{relative: true,url: "?query=string"}, | |
{relative: false,url: "http://www.google.com/path/to/file.ext"}, | |
{relative: false,url: "//www.google.com/path/to/file.ext"}, | |
{relative: false,url: "www.google.com/path/to/file.ext"}, | |
{relative: false,url: "www.google.com"}, | |
{relative: false,url: "google.com/path/to/file.ext"}, | |
{relative: false,url: "https://www.google.com/path/to/file.ext"}, | |
{relative: false,url: "///what-is-this?"}, | |
{relative: false,url: "file:///what-is-this?"}, | |
{relative: false,url: "http://one"} | |
]; | |
console.log("\n%cRunning tests...", "font-weight:bold;font-size:1.2rem"); | |
var successCount = 0, | |
failureCount = 0, | |
failures = []; | |
for(var i=0; i < testData.length; i++){ | |
if(isRelative(testData[i].url) == testData[i].relative){ | |
successCount++; | |
}else{ | |
failures.push({ | |
index: i, | |
result: isRelative(testData[i].url), | |
data: testData[i] | |
}); | |
failureCount++; | |
} | |
} | |
console.log( | |
"Tests complete: " + | |
failureCount + " failed %o, " + | |
successCount + " succeeded, " + | |
"total: " + testData.length, | |
failures | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment