JavaScript Notes
Master URL validation in JavaScript using regex patterns. Learn protocols, domains, paths, query strings with practical code examples.
Introduction
URL validation is an essential part of web development. Whenever you build forms, accept user input, or work with APIs — URL validation is necessary. In this tutorial, we will learn URL validation from basic to production-ready patterns using JavaScript regex.
A URL (Uniform Resource Locator) follows a structured format. With regex, we can validate each part individually or collectively. We will cover basic patterns through to production-ready solutions.
Is guide mein aap seekhenge:
- Matching different parts of a URL using regex
- Basic se advanced URL patterns
- Real-world form validation examples
- Common mistakes and how to avoid them
- Interview mein puche jaane wale questions
URL Regex Patterns
Pattern 1: Basic URL Validation
The simplest pattern that checks whether a URL starts with http or https:
const basicURLRegex = /^https?:\/\/.+/;
console.log(basicURLRegex.test("https://example.com"));
console.log(basicURLRegex.test("http://test.org"));
console.log(basicURLRegex.test("ftp://files.com"));
console.log(basicURLRegex.test("example.com")); true true false false
Pattern 2: Full URL with Named Groups
This pattern captures each part of the URL separately using named groups:
Protocol: https Domain: www.example.com Port: 8080 Path: /products/list Query: category=js&sort=new Hash: top
Pattern 3: Domain Only Validation
To validate only the domain name without the protocol:
true true false false true
Pattern 4: URL with Optional Path and Query
true true true false
Code Examples
Example 1: Basic URL Checker Function
true true true false false
Example 2: URL Validation With and Without WWW
https://www.example.com → true https://example.com → true http://www.test.org/page → true http://test.org/page → true https://blog.example.com → true www.example.com → false
Example 3: Validate Specific Domains Only
{ valid: true, domain: "github.com" }
{ valid: true, domain: "docs.github.com" }
{ valid: false, domain: "evil-site.com" }
{ valid: true, domain: "stackoverflow.com" }Example 4: URL with Query Parameters Extraction
{
"protocol": "https",
"host": "shop.example.com",
"port": "443",
"path": "/products/search",
"params": {
"category": "electronics",
"brand": "samsung",
"page": "2"
},
"fragment": "results"
}Example 5: new URL() Constructor Approach vs Regex
URL Constructor Regex ------------------------------------------------------------ https://example.com true true http://localhost:3000 true false https://192.168.1.1/admin true false https://example true false javascript:alert(1) false false https://valid-site.com/path?q=hello true true
Example 6: Real Form Validation with Error Messages
{ valid: true, errors: [] }
{ valid: false, errors: ["URL cannot contain spaces", "Invalid domain format"] }
{ valid: false, errors: ["URL must start with http:// or https://", "Invalid domain format"] }
{ valid: true, errors: [] }
{ valid: false, errors: ["URL field is required"] }Example 7: URL Sanitizer and Validator Combined
{ original: " WWW.Example.COM ", sanitized: "https://www.example.com", valid: true }
{ original: "HTTPS://BLOG.SITE.ORG/Post", sanitized: "https://blog.site.org/Post", valid: true }
{ original: "example.com/", sanitized: "https://example.com", valid: true }
{ original: "not a valid url at all!", sanitized: "https://not a valid url at all!", valid: false }Regex vs URL Constructor — Detailed Comparison
| Feature | Regex Approach | URL Constructor |
|---|---|---|
| Browser Support | All browsers | Modern browsers (not in IE) |
| Strictness | Customizable | Lenient (allows https://example) |
| Performance | Fast for simple checks | Object creation overhead |
| Custom Rules | Easy to add domain restrictions | Harder to restrict |
| Error Messages | Can give specific errors | Only valid/invalid |
| IP Address URLs | Need explicit pattern | Automatically handles |
| Internationalized URLs | Complex to handle | Built-in support |
| XSS Prevention | Must explicitly block javascript: | Check protocol after parsing |
| Best For | Form validation, specific format enforcement | General URL parsing, API work |
Recommendation: In production applications use a combination of both — new URL() for parsing and regex for specific format enforcement.
true false false true
🚫 Common Mistakes
Mistake 1: Forgetting to Escape Forward Slashes
// ❌ WRONG — slashes not escaped
const wrong = /^https?://.+/; // SyntaxError!
// ✅ CORRECT — slashes escaped
const correct = /^https?:\/\/.+/;
console.log(correct.test("https://example.com"));true
Mistake 2: Not Anchoring the Pattern
true false
Mistake 3: Not Handling Case Sensitivity
false true
Mistake 4: Allowing javascript: Protocol (XSS Vulnerability)
// ❌ WRONG — allows any protocol
const anyProtocol = /^\w+:\/\/.+$/;
console.log(anyProtocol.test("javascript://alert(1)"));
// ✅ CORRECT — explicitly allow only http/https
const safeProtocol = /^https?:\/\/.+$/;
console.log(safeProtocol.test("javascript://alert(1)"));true false
Mistake 5: Overly Strict TLD Validation
false false true true
Mistake 6: Catastrophic Backtracking
true
🎯 Key Takeaways
- Use
new URL()for simple checks — it's the browser's built-in parser and handles edge cases.
- Use regex for specific format enforcement — like allowing only HTTPS, restricting to specific domains, or validating query parameters.
- Always use
^and$anchors — without anchors, regex can match partial strings, which is a security risk.
- Explicitly block the
javascript:protocol — this is critical for preventing XSS attacks.
- Don't forget the case-insensitive flag (
i) — protocol and domain in URLs are case-insensitive.
- Combine both approaches in production — regex format check + URL constructor parsing = robust validation.
- Don't overly restrict TLDs — new TLDs are constantly being added (.app, .dev, .technology, etc.).
- Avoid nested quantifiers — they can cause catastrophic backtracking and freeze the app.
- Always sanitize user input first — trim, lowercase protocol/domain, add missing protocol if needed.
- Make sure to test edge cases — IP addresses, ports, international domains, very long URLs, special characters.
❓ Interview Questions
Q1: What is the difference between Regex and URL Constructor for URL validation?
Answer: Regex gives you exact format control — you can specify which characters, protocols, or domains are allowed. The URL Constructor (new URL()) is the browser's built-in parser and handles edge cases, but gives less granular control over the exact format.
Q2: How do you prevent XSS in URL validation?
Answer: To prevent XSS: (1) Only allow http: and https: protocols — block javascript:, data:, vbscript:. (2) Sanitize the URL before inserting into DOM. (3) Use Content Security Policy headers.
false true
Q3: What is catastrophic backtracking and how do you avoid it in URL regex?
Answer: Catastrophic backtracking occurs when the regex engine has to try an exponential number of paths — usually due to nested quantifiers (e.g., (a+)+). In URL regex, this happens when the domain or path section has overly greedy patterns. Prevention: Use atomic groups, possessive quantifiers, or simpler non-backtracking patterns.
Q4: How do you validate International Domain Names (IDN) with regex?
Answer: International domain names (like münchen.de or 例え.jp) are punycode encoded (e.g., xn--mnchen-3ya.de). Validating Unicode domains directly with regex is complex. The best approach is to first convert to punycode using a library, then validate.
Q5: What is the best approach for URL validation in a production application?
Answer: For production-ready URL validation, follow this strategy:
{ valid: true, parsed: URL { href: "https://example.com/", ... } }
{ valid: false, reason: "Invalid protocol" }📝 FAQ
Q: Is 100% accurate URL validation possible with regex?
A: No, fully RFC 3986 compliant URL validation with regex alone is practically impossible because the URL specification is very complex. In real-world applications, a regex that covers 95%+ of cases is sufficient. For full compliance, use the new URL() constructor.
Q: Does new URL() work in all browsers?
A: new URL() is supported in all modern browsers (Chrome, Firefox, Safari, Edge). It's not supported in Internet Explorer, but IE is practically dead in 2026. It's also fully supported in Node.js.
Q: What is the most common security vulnerability in URL validation?
A: The most common vulnerability is allowing javascript: protocol URLs. If you use user input in an anchor tag's href or in window.location without validation, attackers can inject malicious scripts. Always whitelist allowed protocols (http, https, mailto).
Q: How do you validate URLs with IP addresses using regex?
A: For IP address URLs, you need to add a separate pattern:
const ipURLRegex = /^https?:\/\/(\d{1,3}\.){3}\d{1,3}(:\d{1,5})?(\/\S*)?$/;
console.log(ipURLRegex.test("http://192.168.1.1:8080/api"));
console.log(ipURLRegex.test("https://10.0.0.1/admin"));true true
Note: This pattern doesn't validate IP ranges (it would allow values over 255). For complete validation, check each octet separately or use the URL constructor.
Q: How do you handle localhost URLs in development?
A: To allow localhost and custom ports in a development environment:
true true true false
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript URL Validation with Regex — Complete Patterns & Examples 2026.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, regex, url, validation
Related JavaScript Master Course Topics