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:
xxxxxxxxxx
1
var EXPRESSION = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
2
3
var url = 'https://dirask.com/snippets?type=bash&page=5';
4
var result = EXPRESSION.test(url);
5
6
console.log('The URL is ' + (result ? 'correct' : 'incorrect'));
Output:
xxxxxxxxxx
1
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.
In this example, we create a reusable arrow function that validates the url
passed as an argument returning true
or false
.
xxxxxxxxxx
1
const EXPRESSION = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
2
3
const validateUrl = (url) => EXPRESSION.test(url);
4
5
6
// Usage example:
7
8
console.log(validateUrl('https://dirask.com/snippets?type=bash&page=5')); // true