Wednesday 27 February 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...