Lodash _.isRegExp() method
What you’ll learn
- How
_.isRegExp(value)confirms a realRegExpinstance. - Why strings and ordinary objects fail even when they look regex-ish.
- How literals and
new RegExp()both qualify. - Where guards belong before calling
.test,.exec, or string methods that expect a pattern.
Prerequisites
You know a regex literal (/pattern/) differs from a string that holds characters.
- You have used
RegExpor regex literals in matching code. - Try-it labs load lodash from the CDN.
Overview
Use _.isRegExp when APIs accept “pattern or string” unions and you must branch to safe regex operations only for genuine RegExp objects.
Native instances
Literals and new RegExp() both register as RegExp.
Strings fail
A pattern-shaped string is still a string per lodash docs.
Guard rails
Validate before .test / match pipelines assume a regex.
Syntax
_.isRegExp(value) - value: any value to test.
- Returns:
trueifvalueis a RegExp object; otherwisefalse.
Literals and new RegExp()
Both creation styles produce instances lodash recognizes.
import isRegExp from "lodash/isRegExp";
console.log(
"literal: " + isRegExp(/pattern/) + "\n" + // true
"ctor: " + isRegExp(new RegExp("dynamic", "i")) // true
); String patterns and plain objects
The lodash docs emphasize _.isRegExp("/abc/") === false—a string is never classified as a regexp.
import isRegExp from "lodash/isRegExp";
console.log(
"slashStr: " + isRegExp("/abc/") + "\n" + // false (lodash docs)
"plainObj: " + isRegExp({ source: "x" }) // false
); Primitives and nullish values
Numbers and booleans are out; null and undefined never qualify.
import isRegExp from "lodash/isRegExp";
console.log(
"num: " + isRegExp(42) + "\n" + // false
"nullVal: " + isRegExp(null) + "\n" + // false
"undef: " + isRegExp(undefined) // false
); 📋 _.isRegExp vs related checks
| API / pattern | Behavior |
|---|---|
_.isRegExp(x) | true only for actual RegExp instances. |
x instanceof RegExp | Similar in one realm; breaks across frames/realms sometimes. |
typeof x === "object" | Too broad—arrays and dates also satisfy typeof object. |
Object.prototype.toString.call(x) | Manual [object RegExp] tag—lodash wraps this idea. |
Pitfalls to avoid
Do not coerce blindly
User input that “looks like” /.../ is still a string until you compile it explicitly.
No regex in JSON
Serialization drops regex; deserialize patterns as strings and rebuild with new RegExp when needed.
Union types
When a parameter accepts string | RegExp, branch on _.isRegExp before assuming regex methods exist.
❓ FAQ
Summary
- Purpose: guarantee a value is a native-style RegExp before regex-specific work.
- Remember: strings and POJO stand-ins always return
false. - Next: explore more on Lodash _.isSafeInteger().
The lodash docs show _.isRegExp("/abc/") as false—a string that looks like a pattern is still just a string until you pass it to new RegExp().
6 people found this page helpful
