This question is a spin-off of [] is an instance of Array but "" isn't of String
Given that
"" instanceof String; /* false */
String() instanceof String; /* false */
new String() instanceof String; /* true */
and
typeof "" === "string"; /* true */
typeof String() === "string"; /* true */
typeof new String() === "string"; /* false */
Then, if I have a variable abc
and I want to know if it's a string, I can do
if(typeof abc === "string" || abc instanceof String){
// do something
}
Is there a simpler, shorter and native way of doing this, or must I create my own function?
function isStr(s){
return typeof s === "string" || s instanceof String;
}
if(isStr(abc)){
// do something
}
We can use the isdigit() function to check if the string is an integer or not in Python. The isdigit() method returns True if all characters in a string are digits. Otherwise, it returns False.
Method #1 : Using isinstance(x, str) This method can be used to test whether any variable is a particular datatype. By giving the second argument as “str”, we can check if the variable we pass is a string or not.
The typeof operator is used to obtain the System. Type object for a type. It is often used as a parameter or as a variable or field. It is used to perform a compile time lookup i.e. given a symbol representing a Class name, retrieve the Type object for it.
I think Object.prototype.toString.call(a) === "[object String]"
is the shortest/nativest way of doing this
you are correct:
typeof myVar == 'string' || myVar instanceof String;
is one of the best ways to check if a variable is a string.
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