The most straightforward method of getting a variable type in javascript is
using the typeof operator:
In a simple case
| 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 :
| 'string text'
"string text"
Or, using the ``String`` global object directly:
|
| String(thing)
new String(thing)
|
Now that is where it becomes a bit tricky:
| 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:
| so instanceof String
>> true
|
The code
| isString = function(s) {
return typeof(s) == 'string' || s instanceof(String);
}
isString('abc')
>> true
isString(new String('abc'))
>> true
isString(321)
>> false
|
References