How to Determine if a JavaScript String Represents a URL
In JavaScript, you may encounter scenarios where you need to determine if a given string is a valid URL. While regular expressions offer a versatile approach, certain URL formats, such as "stackoverflow," lack standard elements like ".com," "www," or "http."
To handle such cases, a more robust method is utilizing the URL constructor.
Solution:
To check if a string represents a valid HTTP URL, you can employ the following function:
function isValidHttpUrl(string) { try { const url = new URL(string); return url.protocol === "http:" || url.protocol === "https:"; } catch (_) { return false; } }
This function will instantiate a new URL object with the provided string. If the string adheres to the proper URL format, it will succeed without throwing an error.
Note:
It's important to consider that not all URLs must start with "http" or "https." According to RFC 3886, URLs can commence with various schemes. Here are some examples:
The above is the detailed content of Is Your JavaScript String a Valid URL?. For more information, please follow other related articles on the PHP Chinese website!