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]);
- The regular expression representing the search pattern must be enclosed in quotation marks or slashes (
/). - 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.
RegExp.prototype.exec()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.
RegExp.prototype.globalRegExp.prototype.ignoreCaseRegExp.prototype.multilineRegExp.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. |