Check if a variable is a string in JavaScript
To identify a string, leverage typeof
:
Do a more thorough string identification by combining typeof
and instanceof
:
Solid check with Object.prototype.toString
When battling with those perplexing objects or dealing with prototype sorcery, Object.prototype.toString.call()
comes to rescue like a true superhero, returning a robust [object String]
for a certified string scenario.
String validation with external libraries
Both lodash and jQuery have their own armory for battling the "Is this a string?" question. With lodash, you'd wield _.isString(myVar)
. Brandishing jQuery, you'd defend with $.type(myVar) === "string"
. Clear, concise, and probably a tad cooler!
Maneuvering potential pitfalls and corner cases
A fair warning, my friend: Using typeof
on a new String("example")
returns you 'object'
. Say what? Yes, it sees a string object and calls it an 'object'. And believe me or not, typeof
can't tell a regular string from a disguised string (like a proxy around a string). Combining typeof
with Object.prototype.toString.call()
helps you outsmart these tricksy cases.
Differentiating primitive strings and String objects
Respecting best practices
Google and Douglas Crockford suggest to avoid using string object wrappers like new String()
. They don't improve your JavaScript balance but sure do contribute to the tricky parts. So, let's stick to primitive strings and enjoy a life with fewer surprises!
The power of unit testing
Conducting unit tests ensures that your string recognition logic holds water. Test it in diverse scenarios. Proxies? Check. Falsy values? Check. Objects trying to fool you into thinking they're strings? Check. False alarms and misses? Consider them beaten!
Was this article helpful?