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:

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

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

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

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

// Accepting URLs such as 'url.com/something'
pattern = /^(http(s)?\:\/\/)?(www\.)?[a-zA-Z0-9-]+\.[a-z]+(\/[a-zA-Z0-9-]+)?$/;
pattern.test('https://erikmartinjordan.com/blog'); // 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:

javascript
/* -----------------------------------------------------------
   ^        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.