Search⌘ K
AI Features

Special Characters: Matching the Protocol and Hostname

Explore how to construct regular expressions in JavaScript to accurately match URL protocols like http, https, and ftp, and hostnames with optional www prefixes and .com domains. Understand the use of optional characters, groups, and escaping special characters to create precise matching patterns for web addresses.

Regular expression to match the protocol

This part is easy. There aren’t that many protocols around, and since our testing strings are quite simple, we can say a protocol is either the string http, https, or ftp, followed by the “://” portion. This is how we can write that in a RegExp:

/(https?|ftp):\/\//g

To double-check what we’ve seen so far (and the new part with the OR operator), let’s break it down:

  • We’re matching both http and https with the addition of the ? character after https ...