TIL check if the URL is valid
POSTED ON:
TAGS: javascript
Brilliant! This uses the web APIs URL() - MDN.
const isValidURL = (url) => {
try {
new URL(url);
return true;
} catch (error) {
return false;
}
};
isValidURL("https://dev.to");
// true
isValidURL("https//invalidto");
// false
new URL('/en-US/docs'); // Raises a TypeError exception as '/en-US/docs' is not a valid URL
new URL('http://www.example.com', ); // => 'http://www.example.com/'
Via 11 JavaScript Tips and Tricks to Code Like A Superhero (Vol.2)](https://dev.to/orkhanjafarovr/11-javascript-tips-and-tricks-to-code-like-a-superhero-vol-2-mp6)
Related TILs
Tagged: javascript