Determining the Validity of a URL String in JavaScript
In the realm of JavaScript, the ability to verify whether a given string qualifies as a URL is a crucial skill. Excluding the use of regular expressions, this task can be effectively achieved.
To ascertain if a string represents a valid HTTP URL, the URL constructor offers a reliable solution. This method triggers an error upon encountering an improperly formatted string. Here's a JavaScript function that leverages this approach:
function isValidHttpUrl(string) { let url; try { url = new URL(string); } catch (_) { return false; } return url.protocol === "http:" || url.protocol === "https:"; }
Note: As defined by RFC 3886, a legitimate URL must commence with a scheme (not restricted to HTTP/HTTPS). Consider the following examples:
The above is the detailed content of How to Validate a URL String in JavaScript Without Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!