How can I check if a var is a string in JavaScript?
I've tried this and it doesn't work...
var a_string = "Hello, I'm a string.";
if (a_string typeof 'string') {
// this is a string
}
How can I check if a var is a string in JavaScript?
I've tried this and it doesn't work...
var a_string = "Hello, I'm a string.";
if (a_string typeof 'string') {
// this is a string
}
Following expression returns true:
Following expression returns true:
Following expression returns false (sic!):
Following expression returns true:
Best and right way (imho):
Combining the previous answers provides these solutions:
or
Now days I believe it's preferred to use a function form of typeof() so...
check for null or undefined in all cases a_string
You were close:
On a related note: the above check won't work if a string is created with
new String('hello')
as the type will beObject
instead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.The
typeof
operator isn't an infix (so the LHS of your example doesn't make sense).You need to use it like so...
Remember,
typeof
is an operator, not a function. Despite this, you will seetypeof(var)
being used a lot in the wild. This makes as much sense asvar a = 4 + (1)
.Also, you may as well use
==
(equality comparison operator) since both operands areString
s (typeof
always returns aString
), JavaScript is defined to perform the same steps had I used===
(strict comparison operator).As Box9 mentions, this won't detect a instantiated
String
object.You can detect for that with....
jsFiddle.
...or...
jsFiddle.
But this won't work in a multi
window
environment (thinkiframe
s).You can get around this with...
jsFiddle.
But again, (as Box9 mentions), you are better off just using the literal
String
format, e.g.var str = 'I am a string';
.Further Reading.