How to Determine if a JavaScript String is a URL
When working with JavaScript strings, it can be crucial to verify whether they represent valid URLs. One may be tempted to dismiss regular expressions due to the potential for URLs to lack common components like ".com" or "www," but there are more robust methods available.
Using the URL Constructor for HTTP Validation
If you specifically need to check for valid HTTP URLs, consider utilizing the URL constructor:
function isValidHttpUrl(string) { let url; try { url = new URL(string); } catch (_) { return false; } return url.protocol === "http:" || url.protocol === "https:"; }
This approach throws an exception for malformed URLs, ensuring reliability. It also adheres to RFC 3886 by verifying the presence of a scheme at the beginning of the URL.
Additional Considerations for URL Validity
It's important to note that URLs follow specific rules beyond having an HTTP scheme:
The above is the detailed content of Is a JavaScript String a Valid URL: How to Determine?. For more information, please follow other related articles on the PHP Chinese website!