Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if variable is String type

Tags:

I'm getting data with ajax, and the result can be either array of results or a string statement like "no results found". How can i tell whether i got any results or not? i tried this approach:

if result == String
    do something

but its not working, just like

if typeof(result) == "string"
    do something

Is there any other function that can help me get the type of the variable? Or maybe i can test it for Array type, it would also be very helpful

like image 489
Leo Avatar asked Nov 29 '13 09:11

Leo


People also ask

How do you check if it is a string type?

To check if a variable contains a value that is a string, use the isinstance built-in function. The isinstance function takes two arguments. The first is your variable. The second is the type you want to check for.

How do you check if a variable is not a string?

Use the isinstance() Function to Check if a Variable Is a String or Not. It is therefore encouraged to use the isinstance() function over the traditional type() . The isinstance() function checks whether an object belongs to the specified subclass.

How do you check if a variable is a type?

Using the typeof Operator The typeof operator is used to check the variable type in JavaScript. It returns the type of variable. We will compare the returned value with the “boolean” string, and if it matches, we can say that the variable type is Boolean.

How do you check if a variable is a string Java?

The Java instanceof keyword is used to check if an object is a certain type. It returns true or false. For example, we can check if a variable is a type of String; we can test classes to see if they are certain types (e.g., is a Birch a Tree or a BoysName?).


1 Answers

use typeof

doSomething(result) if typeof result is 'string'

Note that typeof is an operator not a function so you don't write typeof(result)

You can also do this

doSomethingElse(result) if typeof result isnt 'string'

or even

return if typeof result is 'string'
   doSomething result
else
   doSomethingElse result

See http://coffeescript.org/#conditionals for more on Coffeescript conditionals.

like image 134
Dave Sag Avatar answered Oct 21 '22 02:10

Dave Sag