Skip to main content

VS Code REGEX

Don't Include Comments ^(?![ \t]*//).*<your search term here>

Remove Line Breaks Replace \n\n\n with \n

Regular Expressions

:.*\{
.*\{

JS

JS Regex is useful for:

  • search text a string
  • replace substrings in a string
  • extract information from a string

How does a Regular Expression look like

In JavaScript, a regular expression is an object, which can be defined in two ways.

The first is by instantiating a new RegExp object using the constructor:

const re1 = new RegExp('hey')

The second is using the regular expression literal form:

const re1 = /hey/

You know that JavaScript has object literals and array literals? It also has regex literals.

Meta Characters

  • \d matches any digit, equivalent to [0-9]
  • \D matches any character that’s not a digit, equivalent to [^0-9]
  • \w matches any alphanumeric character (plus underscore), equivalent to [A-Za-z_0-9]
  • \W matches any non-alphanumeric character, anything except [^A-Za-z_0-9]
  • \s matches any whitespace character: spaces, tabs, newlines and Unicode spaces
  • \\S matches any character that’s not a whitespace
  • \0 matches null
  • \n matches a newline character
  • \t matches a tab character
  • \uXXXX matches a unicode character with code XXXX (requires the u flag)
  • . matches any character that is not a newline char (e.g. \n) (unless you use the s flag, explained later on)
  • [^] matches any character, including newline characters. It’s useful on multiline strings

Escaping

These characters are special:

  • \
  • /
  • [ ]
  • ( )
  • { }
  • ?
  • +
  • *
  • |
  • .
  • ^
  • \$

They are special because they are control characters that have a meaning in the regular expression pattern, so if you want to use them inside the pattern as matching characters, you need to escape them, by prepending a backslash:

/^\\\$/
/^\^\$/ // /^\^\$/.test('^') ✅
/^\\$\$/ // /^\\$\$/.test('\$') ✅