Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Check if a variable is a string in JavaScript

How might I decide if a variable is a string or something different in JavaScript?
by

2 Answers

aashaykumar
This is what works for me:

if (typeof myVar === 'string' || myVar instanceof String)
// it's a string
else
// it's something else
sandhya6gczb

if (s && typeof s.valueOf() === "string") {
// s is a string
}

Works for both string literals let s = 'blah' and for Object Strings let s = new String('blah')

Login / Signup to Answer the Question.