String trimming has become a standard in APIs. In JavaScript there is no standard method to do this. So, most libraries like jQuery and MooTools add in their own trim functionality.
Adding a simple trim method is easy. All you need is the following code:String.prototype.trim = function() {
return this.replace(/^\s*|\s*$/g, '');
};
Now you can do the following:" asdf ".trim();
// "asdf"
"asdf".trim();
// "asdf"
This proves really useful. But it could be better. In PHP you can send an optional second parameter to their trim function that allows you to define characters to be trimmed. By default the function trims white space.
You can implement a few String prototypes in JavaScript to achieve similar results. Though, instead of sending a string of characters to be trimmed as in PHP you can send a regular expression to the trimming methods to be applied.String.prototype.ltrim = function(what) {
if(arguments.length === 0)
return this.replace(/^\s*/g, '');
what = what.toString();
what = what.substring(1, what.length - 1);
what = new RegExp('^[' + what + ']*', 'g');
return this.replace(what, '');
};
String.prototype.rtrim = function(what) {
if(arguments.length === 0)
return this.replace(/\s*$/g, '');
what = what.toString();
what = what.substring(1, what.length - 1);
what = new RegExp('[' + what + ']*$', 'g');
return this.replace(what, '');
};
String.prototype.trim = function(what) {
return this
.ltrim(what)
.rtrim(what);
};
This allows you to do the following:" Pushing Buttons ".trim();
// "Pushing Buttons"
" Pushing Buttons ".ltrim();
// "Pushing Buttons "
" Pushing Buttons ".rtrim();
// " Pushing Buttons"
" november ".trim(/\s/);
// "november"
" november ".trim(/\s|n|o|r/);
// "vembe"
"designed".trim(/d|e/);
// "sign"
"designed".rtrim(/d|e/);
// "design"
"Late2009".rtrim(/\d/);
// "Late"
-
How to trim() in JavaScript
2 Comments Posted on November 10th, 2009 Updated on November 10th, 2009
2 Comments
-
Vim
Nov 11, 2009
I'm not really good with JavaScript, was going to ask what does the trim function do? but having read this blog made it simple to understand... great script to minimise white space and shorten words! -
Retro
Mar 30, 2010
Thanks for the great tips! I'm currently learning Javascript and continually coming across different obstacles.
Leave a Comment
-
You
Sep 7, 2010