DeveloperBreeze

Javascript Url Regex Development Tutorials, Guides & Insights

Unlock 1+ expert-curated javascript url regex tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your javascript url regex skills on DeveloperBreeze.

Tutorial

Different Ways to Validate URLs in JavaScript

function validateURL(url) {
    const pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
        '((([a-zA-Z0-9\\-\\.]+)\\.([a-zA-Z]{2,}))|' + // domain name
        'localhost|' + // localhost
        '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
        '(\\:\\d+)?(\\/[-a-zA-Z0-9%_@.&+=~]*)*$', 'i'); // port and path

    return pattern.test(url);
}

console.log(validateURL('https://developerbreeze.com')); // true
console.log(validateURL('ftp://developerbreeze.com')); // false
console.log(validateURL('http://localhost:8080')); // true
console.log(validateURL('invalid-url')); // false
  • Pattern Breakdown:
  • ^(https?:\\/\\/)?: Matches the protocol (http:// or https://).
  • (([a-zA-Z0-9\\-\\.]+)\\.([a-zA-Z]{2,})): Matches domain names.
  • localhost: Matches localhost.
  • ((\\d{1,3}\\.){3}\\d{1,3}): Matches IPv4 addresses.
  • (\\:\\d+)?: Matches the port number.
  • (\\/[-a-zA-Z0-9%_@.&+=~]<em>)</em>$: Matches the path.

Aug 29, 2024
Read More