To check that a JS variable is of a type string, you can use 2 operators: instanceof
and typeof
. Here’s a quick
solution.
if (typeof text === 'string' || text instanceof String) {
// it's a string!
} else {
// it's not a string :(
}
Using only typeof
won’t work in a scenario when the string was created as an object using the new String()
syntax.
const s = new String('javascript string object');
console.log(typeof s); // object
So, if you’re looking to check for both primitive strings and string objects, it’s best to use the check that combines
both typeof
and instanceof
.