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.
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.
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
Typescript check if a value is string
A type guard/predicate function:
function isText(data: any): data is string {
return typeof data === 'string';
};
Easy way to check if a variable is a string?
I think Object.prototype.toString.call(a) === "[object String]"
is the shortest/nativest way of doing this
JavaScript check if variable exists (is defined/initialized)
The typeof
operator will check if the variable is really undefined.
if (typeof variable === 'undefined') {
// variable is undefined
}
The typeof
operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.
However, do note that typeof null
will return "object"
. We have to be careful to avoid the mistake of initializing a variable to null
. To be safe, this is what we could use instead:
if (typeof variable === 'undefined' || variable === null) {
// variable is undefined or null
}
For more info on using strict comparison ===
instead of simple equality ==
, see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
Most compact way to check if a javascript variable is a string and then trim it?
You shouldn't need the ||
. You can just do typeof value === 'string'
; that should suffice.
If you wanna do it the slightly more unreadable way but slightly more compact way, you could do:
let value = array[index]
value = typeof value === 'string' && value.trim() || value
Or a ternary:
let value = array[index]
value = typeof value === 'string' ? value.trim() : value
The way you have it is probably fine, though. A good rule of thumb is to prefer more readable but verbose code (versus less readable but more compact).
@nnnnnn has pointed out an even more compact way:
typeof value === 'string' && (value = value.trim())
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]"
.
How can I check if a string is a valid number?
2nd October 2020: note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point ".
":
function isNumeric(str) {
if (typeof str != "string") return false // we only process strings!
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}
To check if a variable (including a string) is a number, check if it is not a number:
This works regardless of whether the variable content is a string or number.
isNaN(num) // returns true if the variable does NOT contain a valid number
Examples
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
isNaN('') // false
isNaN(' ') // false
isNaN(false) // false
Of course, you can negate this if you need to. For example, to implement the IsNumeric
example you gave:
function isNumeric(num){
return !isNaN(num)
}
To convert a string containing a number into a number:
Only works if the string only contains numeric characters, else it returns NaN
.
+num // returns the numeric value of the string, or NaN
// if the string isn't purely numeric characters
Examples
+'12' // 12
+'12.' // 12
+'12..' // NaN
+'.12' // 0.12
+'..12' // NaN
+'foo' // NaN
+'12px' // NaN
To convert a string loosely to a number
Useful for converting '12px' to 12, for example:
parseInt(num) // extracts a numeric value from the
// start of the string, or NaN.
Examples
parseInt('12') // 12
parseInt('aaa') // NaN
parseInt('12px') // 12
parseInt('foo2') // NaN These last three may
parseInt('12a5') // 12 be different from what
parseInt('0x10') // 16 you expected to see.
Floats
Bear in mind that, unlike +num
, parseInt
(as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt()
because of this behaviour, you're probably better off using another method instead):
+'12.345' // 12.345
parseInt(12.345) // 12
parseInt('12.345') // 12
Empty strings
Empty strings may be a little counter-intuitive. +num
converts empty strings or strings with spaces to zero, and isNaN()
assumes the same:
+'' // 0
+' ' // 0
isNaN('') // false
isNaN(' ') // false
But parseInt()
does not agree:
parseInt('') // NaN
parseInt(' ') // NaN
Related Topics
Running JavaScript in Selenium Using Python
Script Tag in JavaScript String
In JavaScript, Why Is the "This" Operator Inconsistent
Detect Back Button Click in Browser
How to Make Post Requests with the Formdata API
How to Do a Horizontal Scroll on Mouse Wheel Scroll
Getting Mouse Location in Canvas
Html5 - Cross Browser Iframe Postmessage - Child to Parent
How to Iterate Through All Attributes in an HTML Element
How to Draw a Line Between Two Divs
Addeventlistener Not Working in IE8
How to Efficiently Randomly Select Array Item Without Repeats
Remove Property for All Objects in Array
Can JavaScript Connect with MySQL
How to Convert HTML to JSON Using PHP
How to Access the Contents of an Svg File in an <Img> Element