Loudtalks — internet walkie talkie

trim() function for ActionScript and JavaScript

By Alexey Gavrilov on February 7, 2010

Strangely ActionScript doesn’t have trim() function, JavaScript doesn’t have it either.

I needed the one lately and googled it but a few solutions that came up looked weird (using several for() cycles for example). So I came up with this one — if you know how to make it simpler or shorter, l’d be very interested to hear your solution.

Old school style:


function trim(s) {
    return s.match(/^s*(.*?)s*$/)[1];
}

var s = trim(" well done   "); // s = "well done"
 

Modern style:


String.prototype.trim = function() {
    return this.match(/^s*(.*?)s*$/)[1];
}

var s = "   even better  ".trim(); // s = "even better"
 

Enjoy!

(categories: Technology, Solutions box)