How can I detect if a variable is a string?
-
1You might want to use underscore.js, it has methods for this built in documentcloud.github.com/underscore/#isString - in case of isString it uses the method mentioned by user113716Martin Wawrusch– Martin Wawrusch2012-03-09 15:08:44 +00:00Commented Mar 9, 2012 at 15:08
-
2possible duplicate of Check if a variable is a stringPhilipp Kyeck– Philipp Kyeck2014-02-23 22:06:46 +00:00Commented Feb 23, 2014 at 22:06
-
possible duplicate of Check whether variable is number or string in javascriptJonathan Hall– Jonathan Hall2015-08-21 20:12:54 +00:00Commented Aug 21, 2015 at 20:12
9 Answers
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]".
1 Comment
new String() results in an object containing a series of indexed properties, each with a value corresponding to the character at that position. Yes, it will get coerced into a string via Object's toString method, but the fact remains that new String('some string') is not a string, in and of itself. typeof someString === "string" is the correct way to determine if a variable is a string. Whether a variable can be turned into a string is moot; every object that can trace its prototype chain to Object has toStringYou can use typeof to do it, but for a lot of things this is bad design.
if (typeof myVar == "string") {
alert("I'm a string!");
}
1 Comment
Use typeof.
if (typeof foo == 'string')
1 Comment
2 Comments
_ is not defined. Could you specify whether it requires package / specific jQuery version?