How can I determine if a variable is a string or something else in JavaScript?
How can I determine if a variable is a string or something else in JavaScript?
You can use Object.prototype
to make a single comparison , since typeof
will fail if it is an object.
Also, as the question says:
How can I determine if a variable is a string or something else in JavaScript?
Precisely, with this method we can always know what type is the object we are evaluating.
Consider a isString
function similar to this one and try it with a simple string str
, with an object strObjeto
and with a number int
:
var strObjeto = new String('String');
var str = "String";
var int= 10;
console.log(isString(strObjeto));
console.log(isString(str));
console.log(isString(int));
function isString(strValor)
{
var bolString=false;
strTipo=Object.prototype.toString.call(strValor);
console.log("Tipo: "+strTipo);
if (strTipo==="[object String]")
{
bolString=true;
}
return bolString;
}
Result in console:
true
Tipo: [object String]
true
Tipo: [object Number]
false
You can use typeof
, with this you can check if a value is of a certain type, for example:
var value = 'Carlos';
if(typeof value === 'string'){
//es string.
}
Also instanceof
to compare an object of type String
:
var value = new String('Carlos');
if(value instanceof String){
//es string.
}
Using jQuery:
if($.type(myVar) === "string"){
//es string.
}