How do I prove that a variable is a string? [closed]

0

How can I determine if a variable is a string or something else in JavaScript?

    
asked by Carlos Laspina 25.09.2017 в 23:37
source

3 answers

2

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
    
answered by 26.09.2017 / 00:55
source
1

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.   
}
    
answered by 26.09.2017 в 00:03
0

with the function typeof

for example

if(typeof forma == 'string'){}

more info link

    
answered by 25.09.2017 в 23:40