Skip to content

Instantly share code, notes, and snippets.

@mikermcneil
Last active June 15, 2023 13:23
Show Gist options
  • Save mikermcneil/9bfdcc31f5f76a220411c0b7ec38cd8c to your computer and use it in GitHub Desktop.
Save mikermcneil/9bfdcc31f5f76a220411c0b7ec38cd8c to your computer and use it in GitHub Desktop.
A basic introduction to regular expressions in JavaScript with a reference of the notation you'll see on a day to day basis.

Regular Expressions in JavaScript: A crash course

I frequently find myself trying to quickly explain the basics of JavaScript regexp, and doing a hasty or incomplete job. Instead, I'm making this. It is by no means a complete reference. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp for that.

Common syntax

Things that match one character
  • . - any character
  • [abc] - any character that matches one of the characters inside the brackets (in this case "a", "b", or "c")
  • [^abc] - any character that does not match any of the other characters inside the brackets (in this case "a", "b", or "c")
  • \s - any whitespace character
  • \S - any non-whitespace character
Symbols that modify whatever the thing before them matches
  • + - one or more occurrences of whatever came before
  • * - zero or more occurrences of whatever came before
  • ? - zero or exactly one occurrences of whatever came before
Symbols that indicate whether this is a "entirely matches", "starts with", "ends with", or "contains" kind of a check
  • ^ - at the beginning of your regexp means "from the start"
  • $ - at the end of your regexp means "through the end"
Putting it together
  • [a-z0-9] - an alphanumeric character (lowercase) e.g. m or 4
  • [^a-z0-9] - the opposite-- any character which is not alphanumeric (lowercase) e.g. D or &
  • [a-z0-9]+ - one or more alphanumeric characters (lowercase) e.g. m393mkeeu13 or 494913581 or asdgasgd
  • washroo+m? - the word "washroom" but allowing for extra "o"s and with the "m" being optional. e.g. washroom or washroooooooooom or washroooo.

Simple examples

  • /dogfood/ => matches any string that contains "dogfood" -- e.g. "I like to eat dogfood." WILL MATCH.
  • /^dogfood$/ => matches "dogfood". The entire string must be "dogfood". Nothing else matches.
  • /^dogfood/ => matches any string that starts with "dogfood" -- e.g. "dogfood is ok."
  • /dogfood$/ => matches any string that ends with "dogfood" -- e.g. "I like to eat dogfood" (notice no period)

A handful of slightly more complex examples

  • /^[^A-Z0-9]/ => matches any string that STARTS with any character OTHER THAN an uppercase alphabet character or a numeral. e.g. "¿I like to eat dogfood" (because of the ¿)
  • /^[A-Z0-9]/ => matches any string that STARTS with any uppercase alphabet character or a numeral e.g. "I like to eat dogfood" (because of the I)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment