Given a character of strings, we want to determine if the given string is a valid URL address. To do this in JavaScript would take many lines of code along with many conditional statements. Well, thank goodness we can get the job done with a little something called Regular Expressions. Regular Expressions or Regex for short, are a series of special characters that define a search pattern. Show SummaryThis is the Regex code snippet that is used to validate a URL: Table of ContentsRegex ComponentsThe first thing you may notice about our snippet is that it is wrapped in ( AnchorsIn our snippet, the characters QuantifiersQuantifiers set the limits of the string that your regex matches, and they are as followed:
In the first Grouping ConstructsWe haven't discussed this yet, but as you may have guessed, we can group patterns together to further breakdown our string URL. The way we do this is with paranthesese Bracket ExpressionsSimilar to how we can group our pattern in paranthesese, we can also use bracket expressions to specify a range of characters that we want to match; for example. This would match all upper/lower case letters, Character ClassesWith our code breakdown snippet starting to look somewhat similar to our URL validation code snippet, let's discuss another useful tool in Regex called Character Classes. Character Classes defines a set of characters, any one of which can occur in an input string to fulfill a match. We've had some exposure to character classes when we discussed bracket expressions, now let's show some common Character Classes:
Note: Each of the last three character classes can be changed to perform an inverse match by capitalizing the letter character. For example, \D matches a non-digit character. Now we update our snippet breakdown with character classes: Character EscapesBy now you are probably noticing some things that are contradictory in our breakdown snippet like the ( AuthorDocument was created by Demetri Dillard, a Jr. Developer and graduate of Trilogy Schools (Uninversity of Minnesota). |