Detecting a string or number

Ok, I have a case were in a var I might have either a string or a number. (contents coming from elsewhere...)

What is the best way to handle this?

Would this be a case for "try/catch", as i guess that now works? I've not used this before, so could someone show a snippet of how to handle this?

Lets say that "var value;" is either a sting or a number.

How can I tell the difference? (something like "isString()" or "isNumber()" would make this easy......)

TIA
  • Former Member
    Former Member over 10 years ago
    There are several options depending on what you are trying to do.

    If this is either a number, or a string that is also a number, you could call .toNumber() without checking type.

    Similarly, if you need to print the value on the screen, you can just call .toString without checking type.

    If you need to handle the value differently depending on the type it comes back as, you can test its type with the instanceof operator.
    function handler( stringOrNumber )
    {
    if( stringOrNumber instanceof String )
    {
    //process String
    }
    else if ( stringOrNumber instanceof Number )
    {
    //process Number
    }
    }
  • There are several options depending on what you are trying to do.

    If this is either a number, or a string that is also a number, you could call .toNumber() without checking type.

    Similarly, if you need to print the value on the screen, you can just call .toString without checking type.

    If you need to handle the value differently depending on the type it comes back as, you can test its type with the instanceof operator.
    function handler( stringOrNumber )
    {
    if( stringOrNumber instanceof String )
    {
    //process String
    }
    else if ( stringOrNumber instanceof Number )
    {
    //process Number
    }
    }


    Thanks! "Instanceof" should do it!