Easy way to check if a variable is a string?

This question is a side effect of [] - this is an array instance, but "" is not a 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 is a string, I can do

if(typeof abc === "string" || abc instanceof String){
    // do something
}

Is there a simpler, shorter, and own way to do this, or should I create my own function?

function isStr(s){
    return typeof s === "string" || s instanceof String;
}
if(isStr(abc)){
    // do something
}
+5
source share
3 answers

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

+6
source

you're right:

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

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

+1
source

, [] ( ), object, '' , .

- , .

: isString true , ? (?) , , .

It is much more common to ignore the type of a variable and, where it can change, unconditionally convert it to the required type, for example. if you want a string primitive:

function foo(s) {
  s = String(s); // s is guaranteed to be a string primitive
  ...
}

The exception is that functions are overloaded and have different behavior depending on whether a particular argument is a function, an object, or some other. Such overloading is usually not considered a good idea, but many javascript libraries depend on it. In these cases, passing a String object rather than a string primitive can have unexpected consequences.

+1
source

All Articles