Check if a variable is a string in JavaScript

Check if a variable is a string in JavaScript

This is what works for me:

if (typeof myVar === string || myVar instanceof String)
// its a string
else
// its something else

You can use typeof operator:

var booleanValue = true; 
var numericalValue = 354;
var stringValue = This is a String;
var stringObject = new String( This is a String Object );
alert(typeof booleanValue) // displays boolean
alert(typeof numericalValue) // displays number
alert(typeof stringValue) // displays string
alert(typeof stringObject) // displays object

Example from this webpage. (Example was slightly modified though).

This wont work as expected in the case of strings created with new String(), but this is seldom used and recommended against[1][2]. See the other answers for how to handle these, if you so desire.


  1. The Google JavaScript Style Guide says to never use primitive object wrappers.
  2. Douglas Crockford recommended that primitive object wrappers be deprecated.

Check if a variable is a string in JavaScript

Since 580+ people have voted for an incorrect answer, and 800+ have voted for a working but shotgun-style answer, I thought it might be worth redoing my answer in a simpler form that everybody can understand.

function isString(x) {
  return Object.prototype.toString.call(x) === [object String]
}

Or, inline (I have an UltiSnip setup for this):

Object.prototype.toString.call(myVar) === [object String]

FYI, Pablo Santa Cruzs answer is wrong, because typeof new String(string) is object

DRAXs answer is accurate and functional and should be the correct answer (since Pablo Santa Cruz is most definitely incorrect, and I wont argue against the popular vote.)

However, this answer is also definitely correct, and actually the best answer (except, perhaps, for the suggestion of using lodash/underscore). disclaimer: I contributed to the lodash 4 codebase.

My original answer (which obviously flew right over a lot of heads) follows:

I transcoded this from underscore.js:

[Arguments, Function, String, Number, Date, RegExp].forEach( 
    function(name) { 
        window[is + name] = function(obj) {
              return toString.call(obj) == [object  + name + ];
    }; 
});

That will define isString, isNumber, etc.


In Node.js, this can be implemented as a module:

module.exports = [
  Arguments,
  Function, 
  String, 
  Number, 
  Date, 
  RegExp
].reduce( (obj, name) => {
  obj[ is + name ] = x => toString.call(x) == [object  + name + ];
  return obj;
}, {});

[edit]: Object.prototype.toString.call(x) works to delineate between functions and async functions as well:

const fn1 = () => new Promise((resolve, reject) => setTimeout(() => resolve({}), 1000))
const fn2 = async () => ({})

console.log(fn1, Object.prototype.toString.call(fn1))
console.log(fn2, Object.prototype.toString.call(fn2))

Leave a Reply

Your email address will not be published. Required fields are marked *