← Back to all snippets
JAVASCRIPT

Validating URLs with Regular Expressions in JavaScript

Implement robust client-side URL validation using a regular expression in JavaScript to ensure user-provided links are correctly formatted and valid for web applications.

function isValidURL(url) {
    const urlRegex = /^(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/[a-zA-Z0-9]+\.[^\s]{2,}|[a-zA-Z0-9]+\.[^\s]{2,})$/i;
    return urlRegex.test(url);
}

console.log(isValidURL("https://www.example.com/path?query=1#hash")); // true
console.log(isValidURL("ftp://bad.url")); // false
console.log(isValidURL("example.com")); // true (handles without http/https too)
How it works: The `isValidURL` function utilizes a comprehensive regular expression to validate a string as a URL. It supports both `http` and `https` protocols, optional `www` subdomain, and various domain formats, providing a flexible check for common URL patterns in web development contexts.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs