About
This dependency checks if a given value is a string
.
This can be easily done natively with the typeof
operator in JavaScript:
typeof
operator
typeof "foo" === "string"; // true
That’s it, that’s all you need to check if a value is a string in JavaScript.
typeof 123 === "string"; // false
typeof {} === "string"; // false
typeof [] === "string"; // false
typeof null === "string"; // false
typeof undefined === "string"; // false
typeof true === "string"; // false
The typeof
operator covers about 99% of string checks.
instanceof
operator
In the unlikely event that you have to deal with String
objects, you can use the instanceof
operator:
new String("foo") instanceof String; // true
new Object("foo") instanceof String; // true
new Boolean("foo") instanceof String; // false
new Number("foo") instanceof String; // false
new Date("foo") instanceof String; // false
new RegExp("foo") instanceof String; // false
new Error("foo") instanceof String; // false
new Function("foo") instanceof String; // false
new Array("foo") instanceof String; // false
// etc.
But really, you should not use String
objects.
And that’s how you check for a string in JavaScript. No dependencies needed.