214

How can I check if a var is a string in JavaScript?

I've tried this and it doesn't work...

var a_string = "Hello, I'm a string.";

if (a_string typeof 'string') {
    // this is a string
}
alex
  • 479,566
  • 201
  • 878
  • 984
vitto
  • 19,094
  • 31
  • 91
  • 130
  • 1
    possible duplicate of [Check whether variable is number or string in javascript](http://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript) – Jonathan Hall Aug 21 '15 at 20:12
  • This is also a duplicate of [Check if a variable is a string in JavaScript](https://stackoverflow.com/questions/4059147/check-if-a-variable-is-a-string-in-javascript) – Alf Eaton Sep 11 '20 at 13:41

6 Answers6

453

You were close:

if (typeof a_string === 'string') {
    // this is a string
}

On a related note: the above check won't work if a string is created with new String('hello') as the type will be Object instead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.

David Tang
  • 92,262
  • 30
  • 167
  • 149
83

The typeof operator isn't an infix (so the LHS of your example doesn't make sense).

You need to use it like so...

if (typeof a_string == 'string') {
    // This is a string.
}

Remember, typeof is an operator, not a function. Despite this, you will see typeof(var) being used a lot in the wild. This makes as much sense as var a = 4 + (1).

Also, you may as well use == (equality comparison operator) since both operands are Strings (typeof always returns a String), JavaScript is defined to perform the same steps had I used === (strict comparison operator).

As Box9 mentions, this won't detect a instantiated String object.

You can detect for that with....

var isString = str instanceof String;

jsFiddle.

...or...

var isString = str.constructor == String;

jsFiddle.

But this won't work in a multi window environment (think iframes).

You can get around this with...

var isString = Object.prototype.toString.call(str) == '[object String]';

jsFiddle.

But again, (as Box9 mentions), you are better off just using the literal String format, e.g. var str = 'I am a string';.

Further Reading.

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    @Box9 No worries, I'm rep capped anyway :P – alex Jun 08 '11 at 23:45
  • @alex I am now too :o (10 more minutes!) – David Tang Jun 08 '11 at 23:49
  • 3
    @RobG Rep capped is when you have gained the maximum rep for one 24 hour period. After that, upvotes do not count towards your reputation. – alex Jun 08 '11 at 23:53
  • Is it not possible to check if a variable is a string by simply testing for the presence of a member that only strings have? For example: `if(myVar.toUpperCase) alert('I am a string');`? See: http://jsfiddle.net/tb3t4nsx/ – ingredient_15939 Mar 31 '15 at 15:39
  • 1
    @ingredient_15939 it's not really a good way... because of `{ toUpperCase: '' }` – alex Apr 02 '15 at 00:20
16

Combining the previous answers provides these solutions:

if (typeof str == 'string' || str instanceof String)

or

Object.prototype.toString.call(str) == '[object String]'
Alf Eaton
  • 5,226
  • 4
  • 45
  • 50
8

Following expression returns true:

'qwe'.constructor === String

Following expression returns true:

typeof 'qwe' === 'string'

Following expression returns false (sic!):

typeof new String('qwe') === 'string'

Following expression returns true:

typeof new String('qwe').valueOf() === 'string'

Best and right way (imho):

if (someVariable.constructor === String) {
   ...
}
redisko
  • 559
  • 5
  • 4
0

Now days I believe it's preferred to use a function form of typeof() so...

if(filename === undefined || typeof(filename) !== "string" || filename === "") {
   console.log("no filename aborted.");
   return;
}
Master James
  • 1,691
  • 15
  • 19
  • there is no function form of `typeof`, you're just controlling order of operations with those parentheses. Some people may find it more readable in certain circumstances. – jrz Oct 19 '16 at 21:33
  • @Jonz What did you mean by "controlling order of operations"? Thanks. – a20 Apr 14 '18 at 05:16
  • I think later I realized you can check the constructor and prefer it as it in theory I thought would be faster but it's not faster? Example number 4 here show the parentheses usage https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof it's definately more readable and less for a compiler parsing to consider. My guess on the 'order' is possibly a speed issue or related to how the compiler loads the argument stack, I'm not sure. – Master James Apr 15 '18 at 13:08
  • 1
    @a20 order of operations describes the order in which operations are executed for statements that contain multiple operations. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence - parentheses (Operating grouping) have the highest operator precedence and are therefore evaluated first. In this case, the parentheses around `filename` only group a single statement, and are therefore useless and extraneous. It's a good thing this answer has a score of 0 because it's wrong, misleading, and unhelpful; it would be better if it had a negative score. – jrz Jun 05 '18 at 17:08
  • Very informative thanks for the link. So the parentheses are checked & run first? so that should run right away without checking next for other ways of calling aka without parentheses, which would be steps later and slower? no? what am I not understanding about the runtime compiler there. – Master James Jun 07 '18 at 12:55
  • I prefer the constructor method now days, even if the performance monitors still don't say it's faster I figure it should be (and maybe I'm waiting until it does ha ha.) – Master James Mar 15 '19 at 13:59
0

check for null or undefined in all cases a_string

if (a_string && typeof a_string === 'string') {
    // this is a string and it is not null or undefined.
}
Kurkula
  • 6,386
  • 27
  • 127
  • 202
  • 2
    `typeof null` and `typeof undefined` will never return `'string'`, so `typeof a_string` is enough. Sorry for necroposting – Ivan Frolov Dec 24 '19 at 19:58