Vérifiez si une variable est une chaîne en JavaScript

Mots clés : javascriptstringjavascript

meilleur 5 Réponses Vérifiez si une variable est une chaîne en JavaScript

vote vote

97

if (typeof myVar === 'string' || myVar instanceof String) // it's a string else // it's something else 
vote vote

85

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" 
vote vote

72

function isString(x) {   return Object.prototype.toString.call(x) === "[object String]" } 
Object.prototype.toString.call(myVar) === "[object String]" 
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'].forEach(      function(name) {          window['is' + name] = function(obj) {               return toString.call(obj) == '[object ' + name + ']';     };  }); 
module.exports = [   'Arguments',   'Function',    'String',    'Number',    'Date',    'RegExp' ].reduce( (obj, name) => {   obj[ 'is' + name ] = x => toString.call(x) == '[object ' + name + ']';   return obj; }, {}); 
const fn1 = () => new Promise((resolve, reject) => setTimeout(() => resolve({}), 1000)) const fn2 = async () => ({})  console.log('fn1', Object.prototype.toString.call(fn1)) console.log('fn2', Object.prototype.toString.call(fn2))
vote vote

62

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

54

function isString (obj) {   return (Object.prototype.toString.call(obj) === '[object String]'); } 

Questions similaires