...

/

Special Characters: Matching the Protocol and Hostname

Special Characters: Matching the Protocol and Hostname

Look at how the regular expressions are written in JavaScript to match the protocol and hostname of a URL.

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 ...