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)
1 Comment »
RSS feed for comments on this post. TrackBack URI
Leave a comment
-
- Categories:
- Technology
- Life
- Solutions box
- Usability
- Vista
- Recent posts:
- trim() function for ActionScript and JavaScript
- How to be stupid
- Posting the old stuff
- The Magic
- Cloudy day at Loudtalks
- You don’t have to prove
- TechCrunch50 list announced
- Recent translations:
- Recent comments:
- Cardin: I believe with optimisation all of these technologies, Java, Flash, Silverlight, Javascript can achieve much...
- Alexey Gavrilov: @Tunc: Tell them to send with USPS and you should be fine. Non-dutiable limit for incoming mail has...
- Tunc: I bought a running shoe and a watch that record some of your data(heart rate, speed, gps coordinates of places...
- Alexey Gavrilov: Sharing a recent good experience. A Blackberry phone (0.7 kg, under $300 value = non-dutiable if you...
- Alexey Gavrilov: Tracking on Russian Post website may include more information than provided by USPS:...
-
September 2010 M T W T F S S « Feb 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 - Archives:
- February 2010
- December 2009
- January 2009
- October 2008
- September 2008
- April 2008
- March 2008
- February 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
- April 2007
- March 2007
- February 2007
- January 2007
- December 2006
- November 2006
- October 2006
- September 2006
- August 2006
- Feeds:
RSS
Comments RSS










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