How to Check if a JavaScript String is a Valid URL
JavaScript, being the language of the web, has built-in support for working with URLs. One common task that developers encounter is validating whether a given string is a valid URL or not. In this article, we’ll explore different techniques for checking if a JavaScript string is a valid URL.
Approach 1: Regular Expressions
One of the most common techniques for validating URLs is through regular expressions. A regular expression is a pattern that is used to match strings. In this case, we can use a regular expression to match against a string that is meant to represent a URL.
The following regular expression can be used to match against a URL:
const urlRegex = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;Let’s break down this regular expression:
^matches the start of the string(https?|ftp)matches eitherhttp,https, orftp:\/\/matches the://characters[^\s/$.?#]matches any character that is not a whitespace,/,$,.,?, or#.matches any character[^\s]*matches zero or more characters that are not whitespace$matches the end of the string/ispecifies that the regular expression is case-insensitive
Using this regular expression, we can check if a given string is a valid URL as follows:
function isUrl(url) {
const urlRegex = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
return urlRegex.test(url);
}
// Example usage
console.log(isUrl("https://www.example.com")); // true
console.log(isUrl("http://localhost:3000/api/users")); // true
console.log(isUrl("ftp://ftp.example.com/file.txt")); // true
console.log(isUrl("not a valid url")); // falseApproach 2: URL API
Another approach to validating URLs is to use the built-in URL API that is available in modern browsers and Node.js.
The URL API provides a way to parse a URL string into its components (such as the protocol, hostname, path, query parameters, etc.). If a given string is not a valid URL, then attempting to parse it using the URL API will throw an error.
Here’s an example of using the URL API to check if a string is a valid URL:
function isUrl(url) {
try {
new URL(url);
return true;
} catch (e) {
return false;
}
}
// Example usage
console.log(isUrl("https://www.example.com")); // true
console.log(isUrl("http://localhost:3000/api/users")); // true
console.log(isUrl("ftp://ftp.example.com/file.txt")); // true
console.log(isUrl("not a valid url")); // falseIn this example, we create a new URL object using the given string. If the string is a valid URL, then creating the object will succeed and we return true. If the string is not a valid URL, then creating the object will throw an error and we catch it and return false.
Note that the URL API is not available in older browsers, so ifyou need to support older browsers, then you'll need to use a polyfill or fallback to a different approach.
Approach 3: Using a Library
If you’re working with URLs frequently in your application, then it may be worthwhile to use a library that provides URL validation and parsing functionality. Some popular options include:
url-parse: A small and fast library for parsing URLs.valid-url: A library for validating URLs based on various constraints (such as requiring a specific protocol or hostname).url-regex: A regular expression for matching against URLs.
Here’s an example of using the valid-url library to validate URLs:
const validUrl = require('valid-url');
function isUrl(url) {
return validUrl.isUri(url);
}
// Example usage
console.log(isUrl("https://www.example.com")); // true
console.log(isUrl("http://localhost:3000/api/users")); // true
console.log(isUrl("ftp://ftp.example.com/file.txt")); // true
console.log(isUrl("not a valid url")); // falseConclusion
In this article, we’ve explored different techniques for checking if a JavaScript string is a valid URL. Regular expressions provide a simple and flexible way to validate URLs, but can be error-prone and difficult to maintain. The URL API provides a more robust way to validate URLs, but may not be available in older browsers. Using a library can simplify URL validation and provide additional functionality, but may add unnecessary complexity to your application.
Ultimately, the approach you choose will depend on your specific use case and the requirements of your application. By understanding the strengths and weaknesses of each approach, you can make an informed decision and ensure that your application is validating URLs correctly.
More content at PlainEnglish.io.
Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.




