JavaScript Introduction | Regular Expressions | RegExp Object

RegExp Object

The RegExp object is a standard built-in JavaScript object that implements regular expressions.

The syntax for creating a RegExp object is as follows.

Syntax

new RegExp(searchPattern[, flags]);
  1. The regular expression representing the search pattern must be enclosed in quotation marks or slashes (/).
  2. Flags that can change the default search settings can be passed only when needed.

RegExp.prototype Methods

All RegExp instances inherit methods and properties from RegExp.prototype. You can represent regular expressions by using the inherited RegExp.prototype methods.

  1. RegExp.prototype.exec()
  2. RegExp.prototype.test()

exec() Method

The exec() method searches for a specific pattern in the string passed as an argument and returns the string that matches the pattern. If there is no string that matches the pattern, it returns null.

var targetStr = "abbcdefabgh";
var firstResult = /ab+/.exec(targetStr);    // When there are multiple strings that match the pattern
var secondResult = /abbb+/.exec(targetStr); // When there are no strings that match the pattern
firstResult;  // abb -> The first matching string is returned.
secondResult; // null

test() Method

The test() method checks whether the string passed as an argument contains a string that matches a specific pattern. If there is a string that matches the pattern, it returns true; otherwise, it returns false.

var targetStr = "abbcdefabgh";
var firstResult = /ab+/.test(targetStr);    // When there are multiple strings that match the pattern
var secondResult = /abbb+/.test(targetStr); // When there are no strings that match the pattern
firstResult;  // true
secondResult; // false

JavaScript RegExp.prototype Methods

Method Description
exec() Searches for a specific pattern in the string passed as an argument and returns the string that matches the pattern.
test() Searches whether the string passed as an argument contains a string that matches a specific pattern and returns the result as a Boolean value.
toString() Returns a regular expression literal string with the same meaning as the regular expression of the RegExp object.

JavaScript provides various information used by regular expressions through RegExp.prototype properties.

  1. RegExp.prototype.global
  2. RegExp.prototype.ignoreCase
  3. RegExp.prototype.multiline
  4. RegExp.prototype.source

JavaScript RegExp.prototype Properties

Property Description
global Indicates the g flag, which selects all matching parts when comparing the search pattern.
ignoreCase Indicates the i flag, which makes search pattern comparison case-insensitive.
multiline Indicates the m flag, which compares multiline input strings as multiple lines.
source Indicates the string contained in the search pattern.