Check if a variable is a string in JavaScript

ID : 351

viewed : 104

Tags : javascriptstringjavascript

Top 5 Answer for Check if a variable is a string in JavaScript

vote vote

99

This is what works for me:

if (typeof myVar === 'string' || myVar instanceof String) // it's a string else // it's something else 
vote vote

85

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 won't 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.
vote vote

76

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 Cruz's answer is wrong, because typeof new String("string") is object

DRAX's answer is accurate and functional and should be the correct answer (since Pablo Santa Cruz is most definitely incorrect, and I won't 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))

vote vote

65

I recommend using the built-in functions from jQuery or lodash/Underscore. They're simpler to use and easier to read.

Either function will handle the case DRAX mentioned... that is, they both check if (A) the variable is a string literal or (B) it's an instance of the String object. In either case, these functions correctly identify the value as being a string.

lodash / Underscore.js

if(_.isString(myVar))    //it's a string else    //it's something else 

jQuery

if($.type(myVar) === "string")    //it's a string else    //it's something else 

See lodash Documentation for _.isString() for more details.

See jQuery Documentation for $.type() for more details.

vote vote

51

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

I saw that here:

http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/

Top 3 video Explaining Check if a variable is a string in JavaScript

Related QUESTION?