Skip to content

Instantly share code, notes, and snippets.

@psatler
Created April 27, 2019 16:45
Show Gist options
  • Save psatler/cc401c579ebbd58663ec085b1092af26 to your computer and use it in GitHub Desktop.
Save psatler/cc401c579ebbd58663ec085b1092af26 to your computer and use it in GitHub Desktop.

What's regex?

Define a search pattern that can be used to search for things in a string.

Some regex symbols to match patterns

  • .test( . . . ) : returns true or false
  • match( . . . ) : returns the match
  • /patternToLookFor/ig: i and g at the end are flags meaning can insensitiveness and every occurrence, respectively.
  • . : match anything with a wildcard period
  • [ ]: match single characters with multiple possibilities
  • [a-z]: match all lowercased letters of the alphabet
  • [^0-9]/ig: the ^inside brackets matches singles characters not specified. For example, this won't match any number in the entire string, no matter the case.
  • +: one or more times
  • *: zero or more times
  • ^word: matches word at the beginning of the string. Notice it's without the brackets []
  • word$: the $ matches the case at the end of the string
  • \w : every letter and number
  • \W: every non letter and number
  • \d: all numbers
  • \D: all non numbers
  • \s: all whitespaces
  • \S: all non whitespaces
  • { , }: curly brackets for quantity identifiers. It can be inserted a lower bound number and/or upper bound number of characters, or even only one number telling the exact number of characters

Some examples

  1. Using regex to check if a username matches the following requirements:
  • if there are numbers, they MUST be at the end
  • letters can be lowercase and uppercase
  • at least two characters long. Two-letter names can't have numbers A possible pattern would be: /^[A-Za-z]{2,}\d*$/
  1. Using capture groups (written inside parentheses) and the replace method to invert the order of a word:
  • "Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1') returns "Camp Code"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment