I have a javscript function (actually a jQuery plugin) which I will want to call as either
myFunction("some input");
or
myFunction({ "prop": "value 1", "prop2": "value2" });
How do I, in the function, tell the two apart?
In other words, what should go in the if
conditions below?
if (/* the input is a string */)
{
// Handle string case (first of above)
}
else if (/* the input is an object */)
{
// Handle object case (second of above)
}
else
{
// Handle invalid input format
}
I have jQuery at my disposal.
Update: As noted in an answer, if the input is new String('some string')
, typeof(input)
will return 'object'
. How do I test for new String('')
, so I can handle that the same way as ''
?
Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string') . If the typeof operator returns "string" , then the variable is a string.
However, JavaScript strings are considered a primitive datatype, which means they are not objects. This fact is crucial because primitive datatypes do not have methods or properties.
Strings are objects in Python which means that there is a set of built-in functions that you can use to manipulate strings. You use dot-notation to invoke the functions on a string object such as sentence.
if( typeof input === 'string' ) {
// input is a string
}
else if( typeof input === 'object' ) {
// input is an object
}
else {
// input is something else
}
Note that typeof
considers also arrays and null to be objects:
typeof null === 'object'
typeof [ 1, 2 ] === 'object'
If the distinction is important (you want only "actual" objects):
if( typeof input === 'string' ) {
// input is a string
}
else if( input && typeof input === 'object' && !( input instanceof Array ) ) {
// input is an object
}
else {
// input is something else
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With