javascript tutorial - [Solved-5 Solutions] Check if a variable is a string - javascript - java script - javascript array



Problem:

Check if a variable is a string

Solution 1:

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"
click below button to copy the code. By JavaScript tutorial team

Solution 2:

lodash / Underscore.js

if(_.isString(myVar))
   //it's a string
else
   //it's something else
click below button to copy the code. By JavaScript tutorial team

jQuery

if($.type(myVar) === "string")
   //it's a string
else
   //it's something else
click below button to copy the code. By JavaScript tutorial team

Solution 3:

['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'].forEach( 
    function(name) { 
        window['is' + name] = function(obj) {
              return toString.call(obj) == '[object ' + name + ']';
    }; 
});
click below button to copy the code. By JavaScript tutorial team

Solution 4:

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');
click below button to copy the code. By JavaScript tutorial team

Solution 5:

var x = "hello"

if(x === x.toString(){
// it's a string 
}else{
// it isn't
}
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Check if a variable is a string