URL regex

URL

URL regular expressions can be used to verify if a string has a valid URL format as well as to extract an URL from a string.

URL regex that starts with HTTP or HTTPS

HTTP and HTTPS URLs that start with protocol can be validated using the following regular expression

/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/

Test it!
/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/

True

False

Enter a text in the input above to see the result

Example code in Javascript:

var httpRegex = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/;
// Validate URL
httpRegex.test('https://uibakery.io'); // Returns true
httpRegex.test('https:/uibakery.io'); // Returns false

// Extract URL from a string
var httpRegexG = /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)/g;
'You can view more details at https://uibakery.io or just ping via email.'.match(httpRegexG); // returns ['https://uibakery.io']

URL regex that doesn’t start with HTTP or HTTPS

The regular expression to validate URL without protocol is very similar:

/^[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/

Test it!
/^[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/

True

False

Enter a text in the input above to see the result

Example code in Javascript:

var httpRegex = /^[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
// Validate URL
httpRegex.test('uibakery.io/contact'); // Returns true
httpRegex.test('/uibakery.io'); // Returns false

// Extract URL from a string
var httpRegexG = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g;
'You can view more details at uibakery.io or just ping via email.'.match(httpRegexG); // returns ['uibakery.io']

Test it!

True

False

Enter a text in the input above to see the result

Notes on URL validation

The above-mentioned regular expressions only cover the most commonly used types of URLs with domain names. If you have some more complex cases you might need a different solution.