Categories
javascript string

Check if a variable is a string in JavaScript

2468

How can I determine whether a variable is a string or something else in JavaScript?

0

    2223

    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.

    12

    • 52

      @Wolfy87 Please be advised that there are some cases that typeof stringValue might return “object” instead of “string”. See comments on my answer.

      – DRAX

      Apr 26, 2012 at 10:07

    • 208

      My preferred answer. The argument against it is that it ‘fails’ for object-wrapped strings like new String('foo'), but that doesn’t matter because object-wrapped strings are a worthless feature that you shouldn’t be using. The Google style guide forbids them, Douglas Crockford wants them deprecated, and no libraries use them. Pretend they don’t exist, and use typeof without fear.

      Jun 6, 2014 at 21:13


    • 8

      Didn’t Douglas Crockford recommend that typeof be deprecated as well?

      – Daniel Le

      Oct 2, 2017 at 9:11

    • 10

      @DanielLe, because he proposed a replacement that fixes some issues, not because he’s against it in principle.

      Dec 6, 2017 at 17:30

    • 5

      If it causes you headaches, 99.99% of the time that’s because you did not structure your code correctly. That’s not NaN’s fault for existing and doing what it does, that’s something you should take note of, learn from, and bear in mind the next time you work with code that might yield it.

      Oct 3, 2018 at 15:44


    2223

    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.

    12

    • 52

      @Wolfy87 Please be advised that there are some cases that typeof stringValue might return “object” instead of “string”. See comments on my answer.

      – DRAX

      Apr 26, 2012 at 10:07

    • 208

      My preferred answer. The argument against it is that it ‘fails’ for object-wrapped strings like new String('foo'), but that doesn’t matter because object-wrapped strings are a worthless feature that you shouldn’t be using. The Google style guide forbids them, Douglas Crockford wants them deprecated, and no libraries use them. Pretend they don’t exist, and use typeof without fear.

      Jun 6, 2014 at 21:13


    • 8

      Didn’t Douglas Crockford recommend that typeof be deprecated as well?

      – Daniel Le

      Oct 2, 2017 at 9:11

    • 10

      @DanielLe, because he proposed a replacement that fixes some issues, not because he’s against it in principle.

      Dec 6, 2017 at 17:30

    • 5

      If it causes you headaches, 99.99% of the time that’s because you did not structure your code correctly. That’s not NaN’s fault for existing and doing what it does, that’s something you should take note of, learn from, and bear in mind the next time you work with code that might yield it.

      Oct 3, 2018 at 15:44


    234

    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))

    22

    • 21

      You recommend underscore.js (for what odd reason?) but you don’t use it here. Moreover you pollute the global namespace with functions. In node.js you’d create a module that’d have all these functions (you can use global || window instead of window but that would be a bad approach to solve a problem you shouldn’t have in the first place).

      Jul 21, 2013 at 12:13


    • 22

      @BenjaminGruenbaum I came looking for the answer to the OP’s question, and didn’t like any of the answers. So I checked what underscore did, and thought it was nifty enough to extract and modify a little (to avoid having to have the underscore library loaded). I’ll clarify my post.

      Aug 3, 2013 at 0:06


    • 31

      @Orwellophile, How is this better than DRAX’s answer?

      – Pacerier

      Jun 20, 2017 at 19:53

    • 6

      JS supports monkey patching, so it’s possible to re-define the toString in the Object.prototype. So, I’d argue that relying on toString to check an object’s type is, at best, a bad practice.

      Jul 26, 2018 at 1:44


    • 9

      i support having “wrong answer” and “shotgun-style answer” refer to post more specifically since the numbers of replies have aged, and then also explain why those answers are inferior as you present superior answer. my two-cents.

      Nov 26, 2019 at 22:13