Comprobar si una variable es una cadena en JavaScript


¿Cómo puedo determinar si una variable es una cadena o algo más en JavaScript?

 1232
Author: ScottyG, 2010-10-30

17 answers

Puede usar el operador typeof:

var booleanValue = true; 
var numericalValue = 354;
var stringValue = "This is a String";
alert(typeof booleanValue) // displays "boolean"
alert(typeof numericalValue) // displays "number"
alert(typeof stringValue) // displays "string"

Ejemplo de esta página web. (El ejemplo fue ligeramente modificado).

 1152
Author: Pablo Santa Cruz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-01 12:35:08

Esto es lo que funciona para mí:

if (typeof myVar === 'string' || myVar instanceof String)
// it's a string
else
// it's something else
 1510
Author: DRAX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-16 19:25:21

Dado que más de 580 personas han votado por una respuesta incorrecta, y más de 800 han votado por una respuesta funcional pero estilo escopeta, pensé que valdría la pena rehacer mi respuesta en una forma más simple que todo el mundo pueda entender.

function isString(x) {
  return Object.prototype.toString.call(x) === "[object String]"
}

O, en línea (tengo una configuración UltiSnip para esto):

Object.prototype.toString.call(myVar) === "[object String]"

Para su información, la respuesta de Pablo Santa Cruz es incorrecta, porque typeof new String("string") es object

La respuesta de DRAX es precisa y funcional, y debería ser la respuesta correcta (ya que Pablo Santa Cruz es definitivamente incorrecto, y no voy a discutir en contra del voto popular.)

Sin embargo, esta respuesta también es definitivamente correcta, y en realidad la mejor respuesta (excepto, quizás, por la sugerencia de usar lodash/underscore ). descargo de responsabilidad: Contribuí a la base de código lodash 4.

Mi respuesta original (que obviamente voló sobre muchas cabezas) sigue:

I transcodificado este de subrayado.js:

['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'].forEach( 
    function(name) { 
        window['is' + name] = function(obj) {
              return toString.call(obj) == '[object ' + name + ']';
    }; 
});

Que definirá isString, isNumber, sucesivamente.


En el nodo.js, esto se puede implementar como un módulo:

module.exports = [
  'Arguments', 
  'Function', 
  'String', 
  'Number', 
  'Date', 
  'RegExp'
].reduce( (obj, name) => {
  obj[ 'is' + name ] = x => toString.call(x) == '[object ' + name + ']';
  return obj;
}, {});
 107
Author: Orwellophile,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-07 17:42:02

Recomiendo usar las funciones integradas de jQueryo lodash/Underscore. Son más fáciles de usar y leer.

Cualquiera de las funciones manejará el caso DRAX mencionado... es decir, ambos comprueban si (A) la variable es un literal de cadena o (B) es una instancia del objeto de cadena. En cualquier caso, estas funciones identifican correctamente el valor como una cadena.

Lodash / Subrayar.js

if(_.isString(myVar))
   //it's a string
else
   //it's something else

JQuery

if($.type(myVar) === "string")
   //it's a string
else
   //it's something else

Ver Documentación de lodash para _.isString () para más detalles.

Consulte la documentación de jQuery para for.escriba () para más detalles.

 77
Author: ClearCloud8,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-22 15:12:21
function isString (obj) {
  return (Object.prototype.toString.call(obj) === '[object String]');
}

Lo vi aquí:

Http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/

 30
Author: ling,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-08 16:14:01

La mejor manera:

var s = 'String';
var a = [1,2,3];
var o = {key: 'val'};

(s.constructor === String) && console.log('its a string');
(a.constructor === Array) && console.log('its an array');
(o.constructor === Object) && console.log('its an object');
(o.constructor === Number || s.constructor === Boolean) && console.log('this won\'t run');

Cada uno de estos ha sido construido por su función de clase apropiada, como "new Object ()", etc.

También, la Tipificación de pato: "Si parece un pato, camina como un pato, y huele como un pato - debe ser una Matriz" Es decir, comprobar sus propiedades.

Espero que esto ayude.

Editar; 12/05/2016

Recuerde, siempre puede usar combinaciones de enfoques también. Aquí hay un ejemplo de uso de un inline map de acciones con tipo de :

var type = { 'number': Math.sqrt.bind(Math), ... }[ typeof datum ];

Aquí hay un ejemplo más del 'mundo real'del uso de inline-maps:

function is(datum) {
    var isnt = !{ null: true, undefined: true, '': true, false: false, 0: false }[ datum ];
    return !isnt;
}
console.log( is(0), is(false), is(undefined), ... );  // >> true true false

Esta función usaría [ custom] "type-casting" rather en lugar de "type-/-value-mapping" to para averiguar si una variable realmente "existe". Ahora puedes dividir ese desagradable cabello entre null & 0!

Muchas veces ni siquiera te importa su tipo. Otra forma de eludir la tipificación es combinar conjuntos de tipos de pato:

this.id = "998";  // use a number or a string-equivalent
function get(id) {
    if (!id || !id.toString) return;
    if (id.toString() === this.id.toString()) http( id || +this.id );
    // if (+id === +this.id) ...;
}

Ambos Number.prototype y String.prototype tener un .toString() method. Simplemente se aseguró de que el equivalente de cadena del número fuera el mismo, y luego se aseguró de pasarlo a la función http como Number. En otras palabras, ni siquiera nos importaba cuál era su tipo.

Esperanza que le da más para trabajar con:)

 18
Author: Cody,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-05 19:02:52

Tomado de lodash:

function isString(val) {
   return typeof val === 'string' || ((!!val && typeof val === 'object') && Object.prototype.toString.call(val) === '[object String]');
}

console.log(isString('hello world!')); // true
console.log(isString(new String('hello world'))); // true
 7
Author: Benj Sicam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-11 01:16:35

Me gusta usar esta solución simple:

var myString = "test";
if(myString.constructor === String)
{
     //It's a string
}
 7
Author: ScottyG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-07 16:01:33

También encontré que esto funciona bien también, y es mucho más corto que los otros ejemplos.

if (myVar === myVar + '') {
   //its string
} else {
   //its something else
}

Al concatenar entre comillas vacías, convierte el valor en una cadena. Si myVar ya es una cadena, entonces la sentencia if tiene éxito.

 6
Author: Chris Dolphin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-27 18:09:00

Si trabaja en el nodo.entorno js, simplemente puede utilizar la función incorporada isString en utils.

const util = require('util');
if (util.isString(myVar)) {}

Editar: como @Jehy mencionó, esto está obsoleto desde v4.

 4
Author: David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-30 20:45:26

Una solución simple sería:

var x = "hello"

if(x === x.toString(){
// it's a string 
}else{
// it isn't
}
 3
Author: Noris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-25 15:00:08
var a = new String('')
var b = ''
var c = []

function isString(x) {
  return x !== null && x !== undefined && x.constructor === String
}

console.log(isString(a))
console.log(isString(b))
console.log(isString(c))
 3
Author: Jake,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-22 04:59:44

Este es un gran ejemplo de por qué el rendimiento importa:

Hacer algo tan simple como una prueba para una cadena puede ser costoso si no se hace correctamente.

Por ejemplo, si quisiera escribir una función para probar si algo es una cadena, podría hacerlo de una de dos maneras:

1) const isString = str => (Object.prototype.toString.call(str) === '[object String]');

2) const isString = str => ((typeof str === 'string') || (str instanceof String));

Ambos son bastante striaght hacia adelante, así que ¿qué podría afectar el rendimiento? En términos generales, las llamadas a funciones pueden ser costosas, especialmente si no saber lo que está pasando dentro. En el primer ejemplo, hay una llamada a función al método toString de Object. En el segundo ejemplo, no hay llamadas a funciones, ya que typeof e instanceof son operadores. Los operadores son significativamente más rápidos que las llamadas de función.

Cuando se prueba el rendimiento, el ejemplo 1 es 79% más lento que el ejemplo 2!

Ver las pruebas: https://jsperf.com/isstringtype

 2
Author: Rob Brander,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-28 15:47:26

Solo para ampliar la respuesta de @DRAX , haría esto:

function isWhitespaceEmptyString(str)
{
    //RETURN:
    //      = 'true' if 'str' is empty string, null, undefined, or consists of white-spaces only
    return str ? !(/\S/.test(str)) : (str === "" || str === null || str === undefined);
}

También tendrá en cuenta los tipos null s y undefined, y se encargará de los tipos que no sean de cadena, como 0.

 1
Author: ahmd0,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:38

El siguiente método comprobará si alguna variable es una cadena (incluyendo variables que no existen).

const is_string = value => {
    try {
        return typeof value() === 'string';
    } catch ( error ) {
        return false;
    }
};

let example = 'Hello, world!';

console.log( is_string( () => example ) );                 // true
console.log( is_string( () => variable_doesnt_exist ) );   // false
 1
Author: Grant Miller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-19 04:33:12

No estoy seguro si te refieres a saber si es un tipo string independientemente de su contenido, o si su contenido es un número o cadena, independientemente de su tipo.

Así que para saber si su tipo es una cadena, eso ya ha sido contestado.
Pero para saber basado en su contenido si es una cadena o un número, usaría esto:

function isNumber(item) {
    return (parseInt(item) + '') === item;
}

Y para algunos ejemplos:

isNumber(123);   //true
isNumber('123'); //true
isNumber('123a');//false
isNumber('');    //false
 -1
Author: Aryeh Beitz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-15 05:22:20

Fichero Completo de Utilidad Para Comprobar todo tipo de variables.

Aquí está la solución completa que, no solo le da una función util básica para averiguar si el valor es un objeto de cadena o cualquier otra cosa. Además de algunos otros buenos para tener funciones.

Este archivo raw se usa en mi proyecto react redux en github Simple React Redux

var Sys = {
    /** This Returns Object Type */
    getType: function(val){
        return Object.prototype.toString.call(val);
    },
    /** This Checks and Return if Object is Defined */
    isDefined: function(val){
        return val !== void 0 || typeof val !== 'undefined';
    }
    /** Run a Map on an Array **/
    map: function(arr,fn){
        var res = [], i=0;
        for( ; i<arr.length; ++i){
            res.push(fn(arr[i], i));
        }
        arr = null;
        return res;
    },
    /** Checks and Return if the prop is Objects own Property */
    hasOwnProp: function(obj, val){
        return Object.prototype.hasOwnProperty.call(obj, val);
    },
    /** Extend properties from extending Object to initial Object */
    extend: function(newObj, oldObj){
        for(var prop in oldObj){
            if(hasOwnProp(oldObj, prop)){
                newObj[prop] = oldObj[prop];
            }
        }
        return newObj;
    } }

['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array'].forEach( 
    function(name) { 
        Sys['is' + name] = function(obj) {
              return toString.call(obj) == '[object ' + name + ']';
    };  });

El código anterior creará un Objeto Sys = {} este método tiene todas las funciones como getType, isDefined Para usarlos, simplemente marque llamar a este método de esta manera.

if(Sys.isDefined(myVar)){ console.log('myVar is defined'); }else { console.log('no myVar is not defined.');}
//Similar to this 
var myStr = 'You are awesome.. !!';
if(Sys.isString(myStr)){console.log(myStr);}
 -2
Author: Tarandeep Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-30 09:30:12