Trim Strings In JavaScript

27. August 2008 12:33

Okay, so you want to trim a string in JavaScript/JScript/EcmaScript, but you find that the functionality just isn't built in.  Here's a quick little snippet that will add said functionality pretty easily.

if (!String.prototype.trim)
    String.prototype.trim = function() {
        return this.toString().replace(/^[\s\r\n]*([\w\W]*?)[\s\r\n]*$/, "$1");

Also... here's a library for extending JS's Date class.

In addition to these little quickies, take a look at prototype.js or jQuery. Both of these frameworks provide some cool things, and though they overlap in terms of functionality, both work very well.

Comments are closed


Michael J. Ryan aka Tracker1

My name is Michael J. Ryan and I've been developing web based applications since the mid 90's.

I am an advanced Web UX developer with a near expert knowledge of JavaScript.