How to check if a string is a valid URL
Short answer
URL.canParse() returns true if the string is a complete address:
console.log(URL.canParse('https://example.com/page'));
console.log(URL.canParse('example.com'));
console.log(URL.canParse('not a url'));Output:
true
false
falseOnly http and https
Strings like javascript:alert(1) are also valid addresses. For links from users, also check the protocol:
const isWebUrl = (value) => {
try {
const url = new URL(value);
return url.protocol === 'http:' || url.protocol === 'https:';
} catch {
return false;
}
};
console.log(isWebUrl('https://example.com'));
console.log(isWebUrl('javascript:alert(1)'));
console.log(isWebUrl('ftp://files.example.com'));Output:
true
false
falseCommon mistake
A regular expression for URLs is easy to get wrong: it either rejects real addresses or lets bad ones through. The URL object parses addresses exactly like the browser does.
const naive = /^https?:\/\/\w+\.\w+$/;
console.log(naive.test('https://example.com/blog'));
console.log(URL.canParse('https://example.com/blog'));Output:
false
trueFunctions used in this recipe
- URL — Parses an address into parts and builds it back.