Trim string in JavaScript?
How do I trim a string in JavaScript? That is, how do I remove all whitespace from the beginning and the end of the string in JavaScript?
All browsers since IE9+ have trim()
method for strings:
" \n test \n ".trim(); // returns "test" here
For those browsers who does not support trim()
, you can use this polyfill from MDN:
if (!String.prototype.trim) {
(function() {
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function() {
return this.replace(rtrim, '');
};
})();
}
That said, if using jQuery
, $.trim(str)
is also available and handles undefined/null.
See this:
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
String.prototype.ltrim=function(){return this.replace(/^\s+/,'');};
String.prototype.rtrim=function(){return this.replace(/\s+$/,'');};
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
The trim from jQuery is convenient if you are already using that framework.
$.trim(' your string ');
I tend to use jQuery often, so trimming strings with it is natural for me. But it's possible that there is backlash against jQuery out there? :)
Although there are a bunch of correct answers above, it should be noted that the String
object in JavaScript has a native .trim()
method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.
if(!String.prototype.trim){
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g,'');
};
}
Added natively in: JavaScript 1.8.1 / ECMAScript 5
Thus supported in:
Firefox: 3.5+
Safari: 5+
Internet Explorer: IE9+ (in Standards mode only!) http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx
Chrome: 5+
Opera: 10.5+
ECMAScript 5 Support Table: http://kangax.github.com/es5-compat-table/
There are a lot of implementations that can be used. The most obvious seems to be something like this:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
" foo bar ".trim(); // "foo bar"
Simple version here What is a general function for JavaScript trim?
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}