Regular expressions

A regular expression is a pattern for matching a string.

Regular expressions are an extremely useful mechanism for extracting information from strings and manipulating their contents. There is an entire lesson on regular expressions - this is just a condensed summary for the purpose of understanding strings.

Creating a regular expression

You can specify a regular expression by writing a pattern between two slash (/) characters, or by creating a RegExp object.

These lessons tend to use the / notation to define regular expressions, but it is worth noticing that all regular expressions are simply RegExp objects regardless of how they are created. You can use the test function of a RegExp object to check if a string matches the pattern.

Loading TypeScript...

Matching a string

The string match function searches a string with a regular expression, and returns an array of matches. If there were no matches, it returns null.

Loading TypeScript...

After the ending slash character (/) of a regular expression, one or more flags can be added to modify the pattern's behavior. The g flag returns all matches in the string, not just the first one.

Loading TypeScript...

The i flag performs a case-insensitive match, and can be combined with the g flag.

Loading TypeScript...

Special regex characters

There are special regex characters like \s, \d, and \w which represent character groups.

  • \w - matches any letter (a - z and A - Z)
  • \d - matches any digit (0 - 9)
  • \s - matches any space character ( , \n, \t)
Loading TypeScript...

The \b character represents a word boundary.

Loading TypeScript...
  • TODO: all groups

Searching a string

The search() method searches a string for a match to a regular expression.

It returns the index of the first match, or -1 if no match is found.

Replacing in a string

The string replace function can replace parts of a string that match a regular expression with a new string.

Loading TypeScript...

The special regex character + matches the preceding pattern one or more times.

Loading TypeScript...

The replacement string can also be a function which accepts the content of each match as an argument.

Loading TypeScript...

Was this page helpful?