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!

Share this!
These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • Technorati
  • Furl
  • Slashdot
  • BlinkList
(categories: Technology, Solutions box)

1 Comment »

  1. Ex-Metalinker Mike Kyurshin commented:

    They use cycles in AS because support for regular expressions only appears in ActionScript 3.0. For JS it is common to use regular expressions: http://www.google.ru/search?q=javascript+trim

    Different ways of regex usage are compared here for example:
    http://blog.stevenlevithan.com/archives/faster-trim-javascript

    Comment by Alexey Gavrilov — February 8, 2010 @ 12:46 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment