How can I check if a var is a string in JavaScript?

vitto picture vitto · Jun 9, 2011 · Viewed 189.4k times · Source

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
}

Answer

David Tang picture David Tang · Jun 9, 2011

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.