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
}
You were close:
if (typeof a_string === 'string') {
// this is a string
}
On a related note: the above check won't work if a string is created with new String('hello')
as the type will be Object
instead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.