My Favorite JavaScript Helper Functions

// @extend // <code> // var obj_1 = {foo:1,bar:{baz:2}}; // var obj_2 = {foo:'test',bar:{qux:'test'}}; // console.log(extend(obj_1, obj_2)); → `{foo:'test',bar:{baz:2,qux:'test'}}` // </code> function extend(defaults, alternates) { defaults = defaults || {}; for (var i in alternates) { if (typeof alternates[i] === "object") { defaults[i] = extend(defaults[i], alternates[i]); } else { defaults[i] = alternates[i]; } } return defaults; } // @edge // Prevent `x` exceeds the value of `min` and `max` function edge(x, min, max) { if (x < min) return min; if (x > max) return max; return x; } // @css // Get CSS value // <code> // console.log(css(document.body, 'font-family')); → `serif` // </code> function css(elem, rule) { var ruleJS = rule.replace(/\-(\w)/g, function(match, $1) { return $1.toUpperCase(); }), value = 0; if (document.defaultView && document.defaultView.getComputedStyle) { value = document.defaultView.getComputedStyle(elem, null).getPropertyValue(rule); } else { value = elem.style[ruleJS]; } return value; } // @array_min // Find min value in array // <code> // console.log(array_min([1,4,58,-4,5,9,87,2,0,-2,.5])); → `-4` // </code> function array_min(arr) { return Math.min.apply({}, arr); } // @array_max // Find max value in array // <code> // console.log(array_max([1,4,58,-4,5,9,87,2,0,-2,.5])); → `87` // </code> function array_max(arr) { return Math.max.apply({}, arr); } // type check function is_set(x) { return typeof x !== "undefined"; } function is_object(x) { return typeof x === "object"; } function is_array(x) { return x instanceof Array; } function is_string(x) { return typeof x === "string"; } function is_number(x) { return typeof x === "number"; } function is_function(x) { return typeof x === "function"; } function is_element(x) { return x instanceof HTMLElement; } function is_regex(x) { return x instanceof RegExp; } // capitalize text function caputalize(text) { return text.toLowerCase().replace(/(^|\W)([a-z])/g, function(a, b, c) { return b + c.toUpperCase(); }); } // camel case function camelize(s) { return s.replace(/\-([a-z])/g, function(a, b) { return b.toUpperCase(); }); } // slug case function dasherize(s) { return s.replace(/([A-Z])/g, function(a, b) { return '-' + b.toLowerCase(); }); } // strip tags function strip_tags(text) { return text.replace(/<.*?>/g, ""); }
Some of them come from PHP, and they are very handy.

4 Responses

It would be great if it had more documentation in comments
capitalize function fails when some characters are used.

Example: Spanish name: "marco ñuñez", results into "Marco ñUñez".
@Marco Piñero Try replace `[a-z]` with `\S`
@Taufik Nurrohman That's the solution! ... Good work!!

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.