JavaScript RegExp toString()
Syntax & Examples
RegExp.toString() method
The toString() method of the RegExp object in JavaScript returns a string representing the regular expression. This method overrides the Object.prototype.toString() method.
Syntax of RegExp.toString()
The syntax of RegExp.toString() method is:
toString()
This toString() method of RegExp returns a string representing the specified object. Overrides the Object.prototype.toString() method.
Return Type
RegExp.toString() returns value of type String
.
✐ Examples
1 Using toString() to get the string representation of a RegExp
In JavaScript, we can use the toString()
method to get the string representation of a regular expression.
For example,
- We create a RegExp object
regex
with the pattern/hello/i
. - We use the
toString()
method to get the string representation ofregex
. - The result is stored in the variable
str
and we log it to the console.
JavaScript Program
const regex = /hello/i;
const str = regex.toString();
console.log(str);
Output
/hello/i
2 Using toString() with a global pattern
In JavaScript, we can use the toString()
method to get the string representation of a regular expression with the global flag.
For example,
- We create a RegExp object
regex
with the pattern/\d+/g
. - We use the
toString()
method to get the string representation ofregex
. - The result is stored in the variable
str
and we log it to the console.
JavaScript Program
const regex = /\d+/g;
const str = regex.toString();
console.log(str);
Output
/\d+/g
3 Using toString() to verify the pattern of a RegExp
In JavaScript, we can use the toString()
method to verify the pattern and flags of a regular expression.
For example,
- We create a RegExp object
regex
with the pattern/abc/i
. - We use the
toString()
method to get the string representation ofregex
. - The result is stored in the variable
str
and we log it to the console. - We verify that the string representation includes both the pattern and the 'i' flag.
JavaScript Program
const regex = /abc/i;
const str = regex.toString();
console.log(str);
Output
/abc/i
Summary
In this JavaScript tutorial, we learned about toString() method of RegExp: the syntax and few working examples with output and detailed explanation for each example.