When working with dynamic data in JavaScript, it's often necessary to validate the types of values, including checking whether a value is a regular expression (RegExp). Lodash provides an elegant and easy-to-use utility function for this: _.isRegExp. This function allows us to verify if a given value is a regular expression or not.
Prerequisites
Install Lodash:
Open your terminal and navigate to your project directory. Run the following command to install Lodash:
npm install lodashApproach
The _.isRegExp function provided by Lodash is specifically designed to check if a value is a regular expression. This method is part of Lodash’s suite of type-checking utilities and provides a straightforward way to perform this check.
Here are several examples demonstrating how to use _.isRegExp to check if a value is a regular expression.
Example 1:This illustrates regex which is a regular expression object, so _.isRegExp(regex) returns true.
const _ = require('lodash');
// Create a regular expression
const regex = /[A-Z]/;
// Check if the value is a regular expression
console.log(_.isRegExp(regex));
Output:
trueExample 2: This illustrates str as a string, not as a regular expression. _.isRegExp(str) returns false.
const _ = require('lodash');
// Create a string
const str = "Welcome to GeeksForGeeks!";
// Check if the value is a regular expression
console.log(_.isRegExp(str));
Output:
falseExample 3: Checking an Object, In this case, obj is a plain JavaScript object and _.isRegExp returns false.
const _ = require('lodash');
// Create a plain object
const obj = { pattern: "[0-9]" };
// Check if the value is a regular expression
console.log(_.isRegExp(obj));
Ouptut:
false