Type checking, detection in javascript. Number, String, Function, Object, Boolean, Regexp
A Pen by Bitcollage on CodePen.
<h2>nice way to check type of:</h2> | |
<ul> | |
<li>number</li> | |
<li>string</li> | |
<li>function</li> | |
<li>object</li> | |
<li>boolean</li> | |
<li>regexp</li> | |
<li>array</li> | |
</ul> | |
<h3>If you use jQuery in your project and want also use "nice way to check type of", please make sure to init it after jQuery loaded!</h3> |
Type checking, detection in javascript. Number, String, Function, Object, Boolean, Regexp
A Pen by Bitcollage on CodePen.
//=============== Global Init ================= | |
Object.prototype.type = function(){ | |
return Object.prototype.toString.call(this).slice(8,-1).toLowerCase(); | |
}; | |
//====================================== | |
// easy way to check type of number, string, etc... ! | |
var foo1 = 123456, | |
foo2 = 'Hello World', | |
foo3 = function(){}, | |
foo4 = {}, | |
foo5 = true, | |
foo6 = /[a-zA-Z]/, | |
foo7 = [1,3,4,5]; | |
console.log(foo1.type()); //numer | |
console.log(foo2.type()); //string | |
console.log(foo3.type()); //function | |
console.log(foo4.type()); //object | |
console.log(foo5.type()); //boolean | |
console.log(foo6.type()); //regexp | |
console.log(foo7.type()); //array | |
// whenever you want just call .type() :) |
h2 { font-family:arial; } |