My Favorite JavaScript Helper Functions

// extend 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; } // 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; } // get CSS value 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; } // trim white-space(s) function trim(text) { return text.replace(/^\s+|\s+$/g, ""); } function ltrim(text) { return text.replace(/^\s+/, ""); } function rtrim(text) { return text.replace(/\s+$/, ""); } // find min and max value in array function array_min(arr) { return Math.min.apply({}, arr); } function array_max(arr) { return Math.max.apply({}, arr); } // type check function is_set(x) { return typeof x !== "undefined"; } function is_array(x) { return typeof x === "object"; } 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_dom(x) { return x instanceof Element && x.nodeName; } function is_regex(x) { return x instanceof RegExp && x.source; } // capitalize text function caputalize(text) { return text.toLowerCase().replace(/(^|\W)([a-z])/g, function(a, b, c) { return b + c.toUpperCase(); }); } // 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.