Wednesday, February 27, 2019

Check if a variable is a string in JavaScript



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.







  1. The Google JavaScript Style Guide says to never use primitive object wrappers.

  2. Douglas Crockford recommended that primitive object wrappers be deprecated.



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...