Languages
[Edit]
EN

JavaScript - validate URL with regex

3 points
Created by:
Iona
445

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

 

 

References

  1. input.js - AngularJS - GitHub

Alternative titles

  1. JavaScript - validate URL with regular expressions
  2. JavaScript - test URL with regex
  3. JavaScript - test URL with regular expressions
  4. JavaScript - check URL with regex
  5. JavaScript - check URL with regular expressions
  6. JavaScript - validate URL with regular expressions
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join