How can I determine whether a variable is a string or something else in JavaScript?
Answer
You can use typeof
operator:
var booleanValue = true;
var numericalValue = 354;
var stringValue = "This is a String";
var stringObject = new String( "This is a String Object" );
alert(typeof booleanValue) // displays "boolean"
alert(typeof numericalValue) // displays "number"
alert(typeof stringValue) // displays "string"
alert(typeof stringObject) // displays "object"
Example from this webpage. (Example was slightly modified though).
This won't work as expected in the case of strings created with new String()
, but this is seldom used and recommended against[1][2]. See the other answers for how to handle these, if you so desire.
- The Google JavaScript Style Guide says to never use primitive object wrappers.
- Douglas Crockford recommended that primitive object wrappers be deprecated.
No comments:
Post a Comment