How to check whether a string is a valid HTTP URL?
How to check whether a string is a valid HTTP URL?
The task of validating the validity of a URL can be simplified by leveraging the in-built URL constructor provided by JavaScript. To perform the validation, an attempt is made to create a new URL object by calling new URL(url). If the string representing the potential URL is well-formed, the operation will be successful, resulting in a valid URL object. However, if the string is not a valid URL, a TypeError is thrown. This method provides a straightforward approach to validation using exception handling.
Here's an example to illustrate this approach:
// Function to check for valid HTTP URL
function isValidHTTPURL(string) {
try {
new URL(string);
return true;
} catch (error) {
return false;
}
}
// Sample test cases
const testCases = ["https://example.com", "http://localhost:8080", "ftp://example.com", "Invalid URL"];
testCases.forEach((testCase) => {
console.log(`"${testCase}" is a valid HTTP URL: ${isValidHTTPURL(testCase)}`);
});
Output:
"https://example.com" is a valid HTTP URL: true
"http://localhost:8080" is a valid HTTP URL: true
"ftp://example.com" is a valid HTTP URL: false
"Invalid URL" is a valid HTTP URL: false
In this example, the isValidHTTPURL function takes a string as input and attempts to create a new URL object using JavaScript's new URL constructor. If the string is a valid HTTP URL, the function returns true. Otherwise, it returns false, indicating that the string is not a valid HTTP URL.
This method provides a simple and effective way to check the validity of a URL string in JavaScript.
- Is a SIM-only plan prepaid?
- Is a SIM card prepaid or postpaid?
- What slows down your Wi-Fi the most?
- Is my SIM post paid or prepaid?
- Why can holding too much cash be harmful to your wealth?
- Can someone check my bank account balance with my account number?
- What are the top 10 cities in the world population?
- Is it better to do a balance transfer or get a loan?
- Is Australia in Celsius or Fahrenheit?
- Where do cruise ship workers live?
Feedback on answer:
Thank you for your feedback! Your input is very important in helping us improve answers in the future.