Skip to content
Advertisement

how to detect if variable is a string

How can I detect if a variable is a string?

Advertisement

Answer

This is the way specified in the ECMAScript spec to determine the internal [[Class]] property.

if( Object.prototype.toString.call(myvar) == '[object String]' ) {
   // a string
}

From 8.6.2 Object Internal Properties and Methods:

The value of the [[Class]] internal property is defined by this specification for every kind of built-in object. The value of the [[Class]] internal property of a host object may be any String value except one of “Arguments”, “Array”, “Boolean”, “Date”, “Error”, “Function”, “JSON”, “Math”, “Number”, “Object”, “RegExp”, and “String”. The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString (see 15.2.4.2).


For an example of how this is useful, consider this example:

var str = new String('some string');

alert( typeof str ); // "object"

alert( Object.prototype.toString.call(str) ); // "[object String]"

If you use typeof, you get "object".

But if you use the method above, you get the correct result "[object String]".

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement