How can I determine whether a variable is a string or something else in JavaScript?
Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string') . If the typeof operator returns "string" , then the variable is a string.
In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.
Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.
${} is a placeholder that is used in template literals. You can use any valid JavaScript expression such as variable, arithmetic operation, function call, and others inside ${}. The expression used inside ${} is executed at runtime, and its output is passed as a string to template literals.
This is what works for me:
if (typeof myVar === 'string' || myVar instanceof String) // it's a string else // it's something else
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With