EN
JavaScript - validate URL with regex
3
points
In this article, we would like to show you how to validate URL in JavaScript using regular expressions (RegExp class).
Quick solution:
// ONLINE-RUNNER:browser;
var EXPRESSION = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
var url = 'https://dirask.com/snippets?type=bash&page=5';
var result = EXPRESSION.test(url);
console.log('The URL is ' + (result ? 'correct' : 'incorrect'));
Output:
The URL is correct
Note:
The most important thing is that there's no single way how to write an expression that validates URL. Some solutions are more precise in checking correctness, others less.
The example above uses expression suggested in AngularJS.
Reusable function
In this example, we create a reusable arrow function that validates the url passed as an argument returning true or false.
// ONLINE-RUNNER:browser;
const EXPRESSION = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
const validateUrl = (url) => EXPRESSION.test(url);
// Usage example:
console.log(validateUrl('https://dirask.com/snippets?type=bash&page=5')); // true