Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to check if a variable is a string?

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
}
like image 705
Oriol Avatar asked Sep 03 '12 23:09

Oriol


People also ask

How do you check if a variable is a string or int?

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.

How do you test if a variable is a string in Python?

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.

How do you check if a variable is a type?

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.


2 Answers

I think Object.prototype.toString.call(a) === "[object String]" is the shortest/nativest way of doing this

like image 96
jbalsas Avatar answered Sep 20 '22 11:09

jbalsas


you are correct:

typeof myVar == 'string' || myVar instanceof String;

is one of the best ways to check if a variable is a string.

like image 40
ajax333221 Avatar answered Sep 19 '22 11:09

ajax333221