Regex Methods

Regex Overview

Regex Methods

🙋 Need help? Ask an expert now!

There are two regex methods that are important to know and are extremely useful when working with regular expressions. The first method is RegExp.test(), which searches for a match in a given string and returns either true or false. The second method is RegExp.exec(). This method searches for the match in a given string and returns an array if the regex is found. If the given regex is not found, the method will return null. Take a look at the sample code below to see how the test() and exec() method are used.

The code above shows two different examples of each method. The first method, test() returns true or false based on whether or not the condition of the regular expression is found in the string. The second method exec() returns an array as shown in the console containing details about the character, index, and the input of the function. The last console.log() statement will return null as the word "Hymn" does not end with the character 'y'.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var literalRegex = /t$/g;
console.log(literalRegex.test("JavaScript Basics Course"));

What will the following code segment print to the console?