既出中の既出なネタですがメモということで。
Javascriptの文字列は2種類あります。
- いわゆる文字列
- Stringオブジェクト
この二つは違うので
var str = 'test message'; var strObj = new String('test message'); console.log(typeof str); // string console.log(typeof strObj); // object console.log(str instanceof String); // false console.log(strObj instanceof String); // true console.log(str == strObj); // true console.log(str === strObj); // false
となります。なので、たとえば文字列およびStringオブジェクトどちらでも良いからとりあえず文字列かどうかを判定する関数を作るなら
function isString(str){ return ((typeof str) == 'string') || (str instanceof String)); }
のようにする必要があります。ご注意を。