JavaScript RegExp()
Syntax & Examples
RegExp constructor
The RegExp constructor in JavaScript creates a new RegExp object for matching text with a pattern. It can be called with or without the 'new' keyword, and optionally accepts flags to modify the behavior of the pattern.
Syntax of RegExp
There are 4 variations for the syntax of RegExp() constructor. They are:
new RegExp(pattern)
This constructor creates a new RegExp object using the given pattern.
new RegExp(pattern, flags)
This constructor creates a new RegExp object using the given pattern and flags.
RegExp(pattern)
This constructor creates a new RegExp object using the given pattern without the 'new' keyword.
RegExp(pattern, flags)
This constructor creates a new RegExp object using the given pattern and flags without the 'new' keyword.
✐ Examples
1 Creating a RegExp object with a string pattern
In JavaScript, we can create a new RegExp object using a string pattern.
For example,
- We create a RegExp object
regex
with the pattern'abc'
. - We test the pattern on the string
'abcdef'
using thetest
method. - We log the result to the console.
JavaScript Program
const regex = new RegExp('abc');
const result = regex.test('abcdef');
console.log(result);
Output
true
2 Creating a RegExp object with flags
In JavaScript, we can create a new RegExp object with a string pattern and flags to modify the behavior of the pattern.
For example,
- We create a RegExp object
regex
with the pattern'abc'
and the flag'i'
for case-insensitive matching. - We test the pattern on the string
'ABCdef'
using thetest
method. - We log the result to the console.
JavaScript Program
const regex = new RegExp('abc', 'i');
const result = regex.test('ABCdef');
console.log(result);
Output
true
3 Creating a RegExp object without the 'new' keyword
In JavaScript, we can create a new RegExp object without using the 'new' keyword.
For example,
- We create a RegExp object
regex
with the pattern'123'
and the flag'g'
for global matching. - We use the
exec
method to find all matches in the string'123 123 123'
. - We log the results to the console.
JavaScript Program
const regex = RegExp('123', 'g');
const result = regex.exec('123 123 123');
console.log(result);
Output
[ '123', index: 0, input: '123 123 123', groups: undefined ]
Summary
In this JavaScript tutorial, we learned about RegExp constructor of RegExp: the syntax and few working examples with output and detailed explanation for each example.