JavaScript Regular Expressions

About JavaScript Regular Expressions

In JavaScript, a regular expression (regex) is a sequence of characters that defines a search pattern.

It is used to handle text manipulation, validation, and pattern matching in JavaScript code.

Creating a Regular Expression

There are two ways to create regular expressions in JavaScript:

Using a regular expression literal:

Regular expression literal consists of a pattern enclosed between forward slashes (/../).

It provides compilation of the regular expression when the script is loaded. If the regular expression remains constant, using this can improve performance.

It needs normal escape (\d).

Example

Using the RegExp Constructor:

Using the RegExp constructor provides runtime compilation of the regular expression.

This is useful when the pattern is not known beforehand and needs to be created dynamically.

It needs double escape (\\d).

Example

Using regular expression literal is faster than using RegExp constructor.

Writing a Regular Expression Pattern

A regular expression pattern can be composed of simple characters, or a combination of simple and special characters.

Pattern of Simple Characters

Simple characters in RegEx are used to match the exact characters in a string.

Pattern characters are enclosed between two (/.../) forward slashes . (example: /cat/)

Example
Explanation of the Code
  • let regEx = /cat/;: This line creates a regular expression object named regEx. The character cat is placed between two forward slashes /cat/. The regular expression /cat/ will be used to search for the literal string "cat" within a given string.
  • regEx.test("Tom is a cat."): JavaScript RegEx method text() is used to check if the regular expression finds a match within the provided string "Tom is a cat.". In this case, the string "Tom is a cat." contains the substring "cat", so the test() method returns true.
  • regEx.test("Jerry is a rat."): JavaScript RegEx method text() is used to check if the regular expression finds a match within the provided string "Jerry is a rat.". The string "Jerry is a rat." does not contain the substring "cat". Therefore, the test() method returns false.

Pattern of Simple and Special Characters (Metacharacters)

JavaScript regular expressions use special characters, also known as metacharacters, along with simple charaters to create powerful search patterns.

In the following example, . (dot) which is a wildcard special character that matches any single character except a newline is used for demonstration. We will learn more about special characters later. Special Characters

Example
Explanation of the Code
  • let regEx = /.at/;: This line creates a regular expression object named regEx. The special character . (dot) is used along with simple characters at to create a pattern. The regular expression /.at/ will be used to search for the literal string that has any charcter at the beginning but ends with "at".
  • regEx.test("Tom is a cat."): JavaScript RegEx method test() is used to check if the regular expression finds a match within the provided string "Tom is a cat.". In this case, the string "Tom is a cat." contains the substring "cat". "cat" matches the regular expression /.at/ because: the . matches the "c" and "at" matches "at". So the test() method returns true.
  • regEx.test("Jerry is a rat."): JavaScript RegEx method test() is used to check if the regular expression finds a match within the provided string "Jerry is a rat.". The string "Jerry is a rat." contains the substring "rat". "rat" matches the regular expression /.at/ because the . matches the "r" and "at" matches "at". Therefore, the test() method returns true.

Regular Expression Methods

JavaScript provides several methods for working with regular expressions which are tied to the RegExp and String objects.

RegExp Methods

1. test()

The RegExp.prototype.test() method tests whether a match is found in a string and returns true or false.

2. exec()

The RegExp.prototype.exec() method executes a search for a match in a string.

If a match is found, the method returns the first match as an array. The array contains the full match string at index 0, index of the match, input string, and captured groups.

If no match is found, it returns null.

String Methods Using RegEx Patterns

1. match()

The String.prototype.match() method searches a string for a match and returns an array if a match is found.

In case of matching, it returns an array of matches if the g global flag is set. It return the array of first match if there's no global flag.

If no match is found, it returns null.

2. matchAll()

The RegExp.prototype.matchAll() method returns an iterator for all matches with detailed match information.

3. replace()

The RegExp.prototype.replace() method searches a string for a match and replaces the first match with a new string.

The regular expression with the global (g) flag replaces all matches.

4. replaceAll()

The RegExp.prototype.replaceAll() method searches a string for a match and replaces all matches with a new string.

The regular expression must include the global (g) flag. Otherwise, JavaScript throws an error.

5. search()

The RegExp.prototype.search() method searches a string for a match and returns the index of the first match.

The method returns -1 if no match is found.

5. split()

The RegExp.prototype.split() method splits a string into an array using a regular expression as the delimiter.

RegEx Pattern Metacharacters

JavaScript regular expressions (RegEx) use special characters, known as metacharacters, to define patterns for matching text. Metacharacters have special meanings and are used to create powerful and flexible search patterns. They are classified based on their functions:

Character Classes

. – Dot (.) matches any single character except a newline (\n). Please note that the period (.) does not take the escape character backslash (\).

\d – Matches any numerical digit from 0 to 9.

\D – Matches any character that is not a digit

\w – Matches any word character (uppercase or lowercase letter, digit, or underscore '_').

\W – Matches any character that is not a word character like spaces, punctuation, etc. (Does not match uppercase or lowercase letter, digit, or underscore '_')

\s – Matches any whitespace character (spaces, tabs, or newlines)

\S – Matches any character that is not a whitespace character

[ ] – Character Set defines a set of characters to match any one of the characters inside the brackets (e.g., [abc] matches 'a', 'b', or 'c'). It just matches only one character at a time not the whole set.

[^ ] – Negation matches any character not in the brackets. The caret (^) inside brackets means negation, not the start of a line.

Quantifiers

Quantifiers in JavaScript regular expressions specify how many times a character, group, or character class should appear in a match.

* – Asterisk (*) matches zero or more occurrences of the preceding character (character before *).

+ – Plus (+) matches one or more occurrences of the preceding character (character before +).

? – Question Mark (?) matches zero or one occurrence of the preceding character, thus makes the character optional.

{n} – Matches exactly n occurrences of the preceding character or group.

{n,} – Matches at least n occurrences.

{n,m} – Matches between n and m occurrences.

Anchors

^ – Caret (^) matches the start of a string.

$ – Dollar ($) matches the end of a string.

\b – Word boundary (\b) matches a position between a word character ([a-zA-Z0-9_]) and a non-word character ([^a-zA-Z0-9_]). A word character is at the start or end of a string. It helps to match an independent word rather than the part of a word.

\B – Non-word boundary (\B) matches positions that are not at a word boundary. The \B ensures the match happens inside a word, not at the boundary (not at the beginning or end).

Regular Expression Flags

g – Global (g) matches all occurrences instead of stopping after the first match.

i – Case-Insensitive (i) matches both uppercase and lowercase letters.

m – Multiline-Matching (m) allows anchors (^ and $) to work across multiple lines. (Without multiline-matching (m), ^ and $ work only on the first line of the string)

s – DotAll (s) flag allows dot (.) to match accross newlines (\n) as well.

u – Unicode (u) flag enables Unicode support to match emojis, symbols, etc.

y – Sticky (y) ensures that the match starts exactly where the last lastIndex property left off in the string. It is used with .exec() method.

Combining Flags: Flags can be combined for greater flexibility. For instance, /aeiou/gi applies both the global (g) and case-insensitive (i) flags, allowing case-insensitive matching across the entire string.

Regular Expression Escaped Characters

\ – Escaped characters are is used to treat special characters (metacharacters) as literal characters or to represent characters that have special meanings.

List of Escaped Characters in JavaScript RegExp
Escape Sequence Meaning
\. Matches a literal dot (.) instead of "any character".
\* Matches a literal * instead of "zero or more occurrences".
\+ Matches a literal + instead of "one or more occurrences".
\? Matches a literal ? instead of "zero or one occurrence".
\^ Matches a literal ^ instead of "start of string".
\$ Matches a literal $ instead of "end of string".
\| Matches a literal | instead of "alternation".
\( Matches a literal ( instead of "start of a capturing group".
\) Matches a literal ) instead of "end of a capturing group".
\[ Matches a literal [ instead of "start of a character set".
\] Matches a literal ] instead of "end of a character set".
\{ Matches a literal { instead of "start of a quantifier".
\} Matches a literal } instead of "end of a quantifier".
\\ Matches a literal backslash (\).

Regular Expression Alternation and Grouping

| – The alternation operator (|) acts like a logical OR. It matches either the pattern before or after the operator.

() – Groups expressions/Parentheses () are used to group parts of a regex together, often to apply operators or capture specific parts of a match.

(?: ) – Non-Capturing Groups ((?: )) are used group items but not capture them for extraction.

More Character Sets & Ranges

[abc] – Matches any character (a, b, or c) inside the brackets.

[^abc] – Matches any character NOT inside the brackets (matches any single character except a, b, or c ).

[a-z] – Matches lowercase letters from a to z

[A-Z] – Matches uppercase letters from A to Z

[a-zA-Z] – Matches lowercase letters from a to z and uppercase letters from A to Z

[0-9] – Matches any numerical digit from 0 to 9

[a-zA-Z0-9] – Matches any alphanumeric character (combination of [a-z], [A-Z] and [0-9] classes)

JavaScript Compiler For Live Practice

Practice the above JavaScript code in the following JavaScript Editor. Create more regular expressions in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.

JavaScript logo JavaScript Editor
JavaScript Code Output