JavaScript - RegExp toString Method
The toString() method in JavaScript is commonly used to retrieve a string representation of an object. When it comes to regular expressions (RegEx), the RegExp.toString() method retrieves a string that represents the regular expression.
In JavaScript, a string is a data type representing a sequence of characters. Which can consist of letters, numbers, symbols, words, or sentences.
Syntax
Following is the syntax of JavaScript RegExp.toString() method −
RegExp.toString()
Parameters
It does not accept any parameter.
Return value
This method returns a string representing the given object (or regular expression).
Examples
Example 1
In the following example, we are using the JavaScript RegExp.toString() method to retrieve a string representing this regular expression "[a-zA-Z]".
<html>
<head>
<title>JavaScript RegExp.toString() Method</title>
</head>
<body>
<script>
const regex = new RegExp("^[a-zA-Z\\s]*$");
document.write("The regex: ", regex);
document.write("<br>Type of regex: ", typeof(regex));
//lets convert to string
const result = regex.toString();
document.write("<br>String representing of this regex: ", result);
document.write("<br>Type of result: ", typeof(result));
</script>
</body>
</html>
Output
The above program returns a string representing of this regex as −
The regex: /^[a-zA-Z\s]*$/ Type of regex: object String representing of this regex: /^[a-zA-Z\s]*$/ Type of result: string
Example 2
If the current regex object is empty, this method will return "/(?:)/".
The following is another example of the JavaScript RegExp.toString() method. We use this method to retrieve a string representing this empty regex ("").
<html>
<head>
<title>JavaScript RegExp.toString() Method</title>
</head>
<body>
<script>
const regex = new RegExp("");
document.write("The regex: ", regex);
document.write("<br>Type of regex: ", typeof(regex));
//lets convert to string
const result = regex.toString();
document.write("<br>String representing of this regex: ", result);
document.write("<br>Type of result: ", typeof(result));
</script>
</body>
</html>
Output
After executing the above program, it will return "/(?:)/".
The regex: /(?:)/ Type of regex: object String representing of this regex: /(?:)/ Type of result: string