JavaScript GetType

Prototype for function to return type of object based on object constructor.

by CheapSk8

JavaScript

function getType() {
  var arg = arguments[0];
  if (typeof(arg) == 'undefined') return null;
  var c = arg.constructor.toString();
  var t = /function\s(.*)\(.*\)/.exec(c);
  return (t.length > 1?t[1]:null);
}
var test = {
    o1: 'string1',
    o2: new String('string2'),
    o3: 1,
    o4: new Number(2),
    o5: new Date(),
    o6: true,
    o7: new Boolean(),
    o8: ['1','2'],
    o9: new Array(3,4),
    o10: new Function('a','b','return a + b'),
    o11: function(c,d) {return c - d;},
    o12: new RegExp('function\s(.*)\(.*\)'),
    o13: /function\s(.*)\(.*\)/
}
document.write('<pre>');
for (k in test) {
    document.writeln(k + ': <b>' + getType(test[k]) + '</b>: <i>' + test[k].toString() + '</i>');
}
document.write('</pre>');