Validate a URL using regex (regular expression)

To validate a basic URL using a regular expression, we'll build a pattern starting with a simple example:

// We'll define a pattern and adjusting it to validate different type of URLs
let pattern;

// Defining pattern for URLs such as ''
pattern = /^[a-zA-Z0-9-]+\.[a-z]+$/;
pattern.test(''); // true

// Accepting 'www.'
pattern = /^(www\.)?[a-zA-Z0-9-]+\.[a-z]+$/;
pattern.test(''); // true

// Accepting 'https:// or http://'
pattern = /^(http(s)?\:\/\/)?(www\.)?[a-zA-Z0-9-]+\.[a-z]+$/;
pattern.test(''); // true 

// Accepting URLs such as ''
pattern = /^(http(s)?\:\/\/)?(www\.)?[a-zA-Z0-9-]+\.[a-z]+(\/[a-zA-Z0-9-]+)?$/;
pattern.test(''); // true

You should use the last pattern to validate all kind of URLs (starting with www, http, https, etc.).

Here you have the cheatsheet of the meaning of the symbols:

/* -----------------------------------------------------------
   ^        Start of string
   [abc]    Include these chars
   +        Check if one or more chars include defined range
   ?        Optional group of chars
   \        Escape special symbol
   $        End of string
----------------------------------------------------------- */

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.