Is it a string?

Posted on Mon 23 September 2013 in articles

The most straightforward method of getting a variable type in javascript is using the typeof operator:

1
2
typeof 'abc'
>> "string"

In a simple case

1
2
s = 'abc'
typeof(s) == 'string'

But what do we know about javascript strings?

The String global object is a constructor for strings, or a sequence of characters. String literals take the forms [1]:
1
2
3
4
  'string text'
  "string text"

Or, using the ``String`` global object directly:
1
2
String(thing)
new String(thing)

Now that is where it becomes a bit tricky:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
s = String('abc')
>> 'abc'
typeof s
>> 'string'
so = new String('abc')
>> { '0': 'a',
     '1': 'b',
     '2': 'c' }
typeof so
>> 'object'  // it is not a 'string' anymore!

And there is nothing wrong with the latter statement as because first of all so is Object created via the new operator. Fortunately the instanceof operator can handle this scenario:

1
2
so instanceof String
>> true

The code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
isString = function(s) {
  return typeof(s) == 'string' || s instanceof(String);
}

isString('abc')
>> true
isString(new String('abc'))
>> true
isString(321)
>> false