Regex in JavaScript

Regular expressions, or regex, are used for searching, validating, replacing, and splitting strings in JavaScript. In this article, you will learn the fundamentals of how to use regex in JavaScript.

In JavaScript, the regular expressions can be used in two ways:

  1. Using Regex Literal Syntax
  2. Using RegExp Constructor

Both the ways are the same. Internally, regex literal syntax uses the RegExp constructor only.

Regex Literal Syntax

The regex literal syntax allows you to define a regex pattern directly within forward slashes / without using quotes.

Regex Literal Syntax:
var regexPattern = /pattern/flags;

After defining a pattern, you can use JavaScript string methods such as match(), search(), replace(), and split() to search, replace, or split based on the regex pattern.

For example, the following defines the regex pattern and uses the string.match() method to match all the digits in the string.

Example: Regex in JavaScript
var regex = /\d/g;
var str = "ABCD1234";
var matches = str.match(regex);
console.log(matches); //output: [ '1', '2', '3', '4' ]

In the above example, the pattern /\d/g uses g flag. So, the match() method returns an array of all matches found in the string.

Regex literal syntax internally uses the RegExp object only. It is just a short syntax of using RegExp object.

RegExp Constructor

The RegExp constructor provides an alternative way to use regex in JavaScript. It takes two arguments: the pattern as a string and an optional flags argument to specify modifiers.

RegExp Constructor:
var regex = new RegExp("pattern", "flags");

The following uses the RegExp object to find a match:

Example: Regex in JavaScript
var regex = new RegExp("\\d","g");
var str = "ABCD1234";
var result = str.match(regex);
console.log(result); 

Use string.matchAll() method to get regex string iterator object that contains all the information about the result.

Example: Regex in JavaScript
var regex = new RegExp("\\d","g");
var str = "ABCD6789";
var matches = str.matchAll(regex);

for (let match of matches) {
   console.log(match);
}

Note that string methods will work in the same way no matter which approch you use for regex.

RegExp Methods

The RegExp constructor provides the methods for pattern matching and manipulation. Visit RegExp for more information.

The RegExp.exec() method returns a match object for the first match found, or null if no match is found.

Example: Regex in JavaScript
var regex = /\d/g;
var str = "ABCD1234";
var match = regex.exec(str);
console.log(match); 

The test() method returns a true if a match is found, otherwise returns a false:

Example: Regex in JavaScript
var regex = /\d/;
var str = "ABCD1234";
var isMatch = regex.test(str);
console.log(isMatch); // Output: true

String Methods for Regex

We have already used the string.match() and string.matchall() methods. There are other string methods which can use Regex expressions.

The string.search() method searches a string for a specified regex pattern and returns the index of the first match found. If no match is found, it returns -1.

Example: Regex in JavaScript
var regex = /\d/g;
var str = "ABCD1234";
var index = str.search(regex);
console.log(index); // Output: 4

The string.replace() method replaces matches of a pattern in a string with a replacement value.

Example: Regex in JavaScript
var regex = /Hello/;
var str = "Hello world!";
var newStr = str.replace(regex, 'Hi');
console.log(newStr); // Output: Hi World!'

The string.split() method splits a string into an array of substrings based on a specified separator, which can be a regex pattern.

Example: Regex in JavaScript
var regex = /-/;
var str = "ABCD-1234-EFGH-5678";
var arr = str.split(regex);
console.log(arr); 

In this example, the split() method splits the string at each hyphen (-) which returns an array of substrings.

Regex Flags

Regex flags are used to modify the behavior of the pattern matching. The following are commonly used flags:

  • g: (global) Matches all occurrences of the pattern in the input string. This is the default flag if no flag is provided.
  • i: (case-insensitive)Matches characters regardless of case.
  • m: (multiline) Allows matching across multiple lines.

Multiple flags can also be used. For example, the pattern /hello/gi matches the word "hello" globally and ignores case sensitivity.