The URL module provides utilities for URL parsing and manipulation. Here's how to use it.
URL Constructor#
Modifying URLs#
URLSearchParams#
Manipulating Query Parameters#
Building URLs#
URL Validation#
URL Encoding#
Practical Patterns#
Common Use Cases#
Best Practices#
Parsing:
✓ Use URL constructor for validation
✓ Use URLSearchParams for queries
✓ Handle parsing errors gracefully
✓ Validate protocols when needed
Building:
✓ Use URL for constructing URLs
✓ Let URLSearchParams handle encoding
✓ Build from trusted base URLs
✓ Sanitize user input
Encoding:
✓ Use encodeURIComponent for values
✓ Let URL handle most encoding
✓ Be careful with double-encoding
✓ Test with special characters
Avoid:
✗ String concatenation for URLs
✗ Manual encoding when not needed
✗ Assuming URL structure
✗ Ignoring edge cases
Conclusion#
The URL module provides robust URL parsing and manipulation. Use the URL constructor for validation and modification, URLSearchParams for query string handling, and proper encoding functions for safety. Build URLs programmatically rather than concatenating strings.