Type Checking in Javascript
A method to test the given type in javascript. Taken from http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
by jamessouth
JavaScript
Object.toType = (function toType(global) {
return function(obj) {
if (obj === global) {
return "global";
}
return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
})(this);
console.log(Object.toType(null)); //=> null (all browsers)
console.log(Object.toType("string")); //=> string (all browsers)
console.log(Object.toType(-1)); //=> number (all browsers)
console.log(Object.toType(NaN)); //=> number (all browsers)
console.log(Object.toType([1,2,3,4,5])); //=> array (all browsers)
console.log(Object.toType({a:"b"})); //=> object (all browsers)
console.log(Object.toType(window)); //=> global(all browsers)
console.log(Object.toType(/a-z/)); //=> regexp (all browsers)
console.log(Object.toType(JSON)); //=> json (all browsers) well except ones without json
console.log(Object.toType(undefined)); //=> undefined (all browsers)
console.log(Object.toType(alert)); //=> function (all browsers)