Check if a variable is a string in JavaScript
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.
- The Google JavaScript Style Guide says to never use primitive object wrappers.
- Douglas Crockford recommended that primitive object wrappers be deprecated.
Check whether variable is number or string in JavaScript
If you're dealing with literal notation, and not constructors, you can use typeof:.
typeof "Hello World"; // string
typeof 123; // number
If you're creating numbers and strings via a constructor, such as var foo = new String("foo")
, you should keep in mind that typeof
may return object
for foo
.
Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),
var toString = Object.prototype.toString;
_.isString = function (obj) {
return toString.call(obj) == '[object String]';
}
This returns a boolean true
for the following:
_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true
How can I check if a var is a string in JavaScript?
You were close:
if (typeof a_string === 'string') {
// this is a string
}
On a related note: the above check won't work if a string is created with new String('hello')
as the type will be Object
instead. There are complicated solutions to work around this, but it's better to just avoid creating strings that way, ever.
How to check if a variable is an integer or a string?
In my opinion you have two options:
Just try to convert it to an
int
, but catch the exception:try:
value = int(value)
except ValueError:
pass # it was a string, not an int.This is the Ask Forgiveness approach.
Explicitly test if there are only digits in the string:
value.isdigit()
str.isdigit()
returnsTrue
only if all characters in the string are digits (0
-9
).The
unicode
/ Python 3str
type equivalent isunicode.isdecimal()
/str.isdecimal()
; only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).This is often called the Ask Permission approach, or Look Before You Leap.
The latter will not detect all valid int()
values, as whitespace and +
and -
are also allowed in int()
values. The first form will happily accept ' +10 '
as a number, the latter won't.
If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.
Dart : How to Check if a variable type is String
Instead of
if(T is String)
it should be
if(_val is String)
The is
operator is used as a type-guard at run-time which operates on identifiers (variables). In these cases, compilers, for the most part, will tell you something along the lines of T refers to a type but is being used as a value
.
Note that because you have a type-guard (i.e. if(_val is String)
) the compiler already knows that the type of _val
could only ever be String
inside your if
-block.
Should you need to explicit casting you can have a look at the as
operator in Dart, https://www.dartlang.org/guides/language/language-tour#type-test-operators.
what is the best way to check variable type in javascript
The best way is to use the typeof
keyword.
typeof "hello" // "string"
The typeof
operator maps an operand to one of six values: "string"
, "number"
, "object"
, "function"
, "undefined"
and "boolean"
. The instanceof
method tests if the provided function's prototype is in the object's prototype chain.
This Wikibooks article along with this MDN articles does a pretty good job of summing up JavaScript's types.
how to detect if variable is a string
This is the way specified in the ECMAScript spec to determine the internal [[Class]] property.
if( Object.prototype.toString.call(myvar) == '[object String]' ) {
// a string
}
From 8.6.2 Object Internal Properties and Methods:
The value of the [[Class]] internal property is defined by this specification for every kind of built-in object. The value of the [[Class]] internal property of a host object may be any String value except one of "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", and "String". The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString (see 15.2.4.2).
For an example of how this is useful, consider this example:
var str = new String('some string');
alert( typeof str ); // "object"
alert( Object.prototype.toString.call(str) ); // "[object String]"
If you use typeof
, you get "object"
.
But if you use the method above, you get the correct result "[object String]"
.
To check if var is String type
if(conditions[name] is string)
{
}
else
{
}
Related Topics
"Importerror: No Module Named Site" on Windows
Tensorflow Only Running on 1/32 of the Training Data Provided
How to Check If Two Segments Intersect
How to Validate a Url in Python? (Malformed or Not)
Python Round Up Integer to Next Hundred
Using Django Time/Date Widgets in Custom Form
Django 1.7 Throws Django.Core.Exceptions.Appregistrynotready: Models Aren't Loaded Yet
How to Know the Angle Between Two Vectors
How to Convert 'Binary String' to Normal String in Python3
How Is _Eq_ Handled in Python and in What Order
Calling Filter Returns <Filter Object at ... >
Weird Try-Except-Else-Finally Behavior with Return Statements
Testing Code That Requires a Flask App or Request Context
How to Get Numbers After Decimal Point
How to Check If a Python Module Exists Without Importing It