// Function to validate a URL using a regular expression
function isValidURL(url) {
const urlRegex = /^(ftp|http|https):\/\/[a-zA-Z0-9-]+(\.[a-zA-Z]{2,})+(\/[^\s]*)?$/;
return urlRegex.test(url);
}
// Example URL to validate
const websiteURL = 'https://www.example.com';
// Check if the URL is valid using the isValidURL function
console.log('Is Valid URL:', isValidURL(websiteURL));JavaScript Validate URL
Related Posts
More content you might like
Different Ways to Validate URLs in JavaScript
- URL Constructor: Provides initial validation, ensuring the string can be parsed as a URL.
- Regex Pattern: Adds an additional layer of validation, covering cases that the constructor might miss.
Validating URLs in JavaScript can be approached in several ways, depending on your needs. The URL constructor is a simple and reliable method for most cases, while regular expressions and third-party libraries offer more customization and coverage. Using HTML5 input fields provides native validation for forms, and combining methods ensures robust validation in production applications.
Checking if the User is Accessing from a Mobile Device in JavaScript
No preview available for this content.
Validating Credit Card Numbers in JavaScript
No preview available for this content.
Detecting Browser and Version
No preview available for this content.
Discussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!