I've been looking at the new URL specification which is now implemented in Chrome Canary, and it looks very useful.
Is there any way to validate a URI before it is passed into the URL object?
For example
var urlToCheck = "http//www.google.com";
if(URL.isValid(urlToCheck)) {
var u = new URL(urlToCheck, baseUrl);
console.log(u.hostname);
}
I can't see anything in the linked specification doc. I would really not like to have to process the thrown Exception just to check the URI is valid.
Actually the 2-parameter version of the URL constructor accepts anything as its first parameter:
try{
new URL(null, 'http://www.example.com');
new URL({ob:'jects',even:{nested:'ones'}}, 'http://www.example.com');
new URL(['arrays'], 'http://www.example.com');
new URL(/regexes/, 'http://www.example.com');
new URL(false, 'http://www.example.com');
new URL(undefined, 'http://www.example.com');
console.log('new URL() takes any value as its first parameter!');
}catch(e){}
This means you don't have to validate both URLs; you only have to validate the base URL. Therefore a simple solution like this should suffice:
URL.isValid = function(url) {
try{
new URL(url);
} catch(e) {
return false;
}
return true;
};
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