This manual will provide the procedure to verify if the JavaScript variable is regex.
How to Check if Variable is Regex in JavaScript?
To verify if a variable is a regex, use the JavaScript “instanceof” operator. It is utilized to determine whether the object is a specific type of instance. As it compares the instance with the type, the operator is also known as a type of Comparison operator.
If an object is an instance of a particular class, the instanceof operator gives true or false as a boolean value, depending on the situation. Moreover, it can be utilized to identify an object’s type at run time.
Syntax
Follow the below-provided syntax to use the “instanceof” operator:
Here, “regexPattern” is a variable that stores a regular expression or a regex, the “RegExp” is a JavaScript object that contains its own properties and methods, and the instanceof operator will check if regexPattern contains a regex or not.
Example 1: Check if Variable has a Regex Pattern
In this example, we will check whether the variable has a regex pattern. To do so, we will first create a variable named “pattern” that stores the following regex pattern or regular expression:
Then, we will check whether the “pattern” variable stores any regex with the help of “instanceof” operator with a ternary (?) operator, which acts like a conditional operator and stores it in a variable called “result”:
Finally, print the result on the console using the “console.log()” method:
As you can see that the output shows “Yes”, which indicates that the string stored in a variable “pattern” is a regex:
If you want to see how a variable follows a regex pattern, follow the next example.
Example 2: Check if Variable Follows a Regex Pattern
In this example, we will check how the variable follows a regex pattern. For this purpose, we will first create a regex pattern stored in a variable named “pattern”:
Then, for verification, call the “test()” method by passing any value. If it matches the pattern, the method will return “true”; else, “false”:
The output displayed “true”, which means the value follows the pattern:
We have provided the simplest approach for determining if a variable is a regex in JavaScript.
Conclusion
To check if a variable is a regex, use the “instanceof” operator. It is used to check the object against a specified type. This operator outputs a boolean value based on whether or not the object is a reference of a particular class. This manual provided the procedure for verifying whether the variable is regex or not with properly defined examples.