How do I remove all whitespace from the start and end of the string?
-
295It's worth mentioning two years after this question was asked that String.trim() was added natively in JavaScript 1.8.1 / ECMAScript 5, supported in: Firefox 3.5+, Chrome/Safari 5+, IE9+ (in Standards mode only!) see scunliffe's answer: http://stackoverflow.com/a/8522376/8432 – wweicker Jan 18 '12 at 18:39
-
47`String.trim()` also works fine out of the box in Node.js. – Brad Jul 05 '12 at 22:41
-
47To nitpick: `String.trim()`, the class method, does not exist in ES5/Node.js; instead, `String.prototype.trim()`, the instance method, exists. Usage: `' foo '.trim()`, not `String.trim(' foo ')`. – frontendbeauty Oct 11 '12 at 23:38
-
3String.trim() works in Google Apps Script too! – Omiod Nov 22 '12 at 11:23
-
40OMG, it's 2013 and IE9 in compat mode has no trim() method on String! – dbrin Jan 09 '13 at 23:25
-
80Worth noting that in jQuery, `$.trim(str)` is always available. – Sygmoral Jan 28 '13 at 19:19
-
1the sad thing is that there are no ltrim and rtrim – BeRocket Nov 27 '13 at 17:34
-
`String.trim()` is only for whitespace chars. Trimming should be more than that in 2016... – user2173353 Jan 12 '16 at 07:39
-
1Refer this example to trim a string using JavaScript : http://javascriptstutorial.com/blog/trim-string/ – Jun 19 '16 at 15:56
-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim – Christophe Roussy Jan 18 '17 at 11:26
20 Answers
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,' ');};

- 136,138
- 45
- 251
- 267

- 10,839
- 4
- 25
- 26
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? :)

- 22,600
- 28
- 79
- 90

- 7,943
- 3
- 23
- 25
-
1this only trims whitespace (newline) .. it does not work like php trim , where you can trim characters as well – Jeffz Jun 22 '13 at 20:43
-
1
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/

- 62,582
- 25
- 126
- 161
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"

- 643,351
- 109
- 780
- 844
Simple version here What is a general function for JavaScript trim?
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}

- 5,503
- 5
- 35
- 54
I know this question has been asked a while back. Now,String.trim()
was added natively in JavaScript. For instance, you can trim directly as following,
document.getElementById("id").value.trim();

- 4,469
- 5
- 39
- 54
-
3This wont work in ie versions, use the jQuery methd $.trim(str) if you can – Ben Taliadoros Apr 18 '13 at 10:15
If you are using jQuery, use the jQuery.trim()
function. For example:
if( jQuery.trim(StringVariable) == '')

- 9,564
- 146
- 81
- 122

- 3,824
- 11
- 58
- 87
Flagrant Badassery has 11 different trims with benchmark information:
http://blog.stevenlevithan.com/archives/faster-trim-javascript
Non-surprisingly regexp-based are slower than traditional loop.
Here is my personal one. This code is old! I wrote it for JavaScript1.1 and Netscape 3 and it has been only slightly updated since. (Original used String.charAt)
/**
* Trim string. Actually trims all control characters.
* Ignores fancy Unicode spaces. Forces to string.
*/
function trim(str) {
str = str.toString();
var begin = 0;
var end = str.length - 1;
while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; }
while (end > begin && str.charCodeAt(end) < 33) { --end; }
return str.substr(begin, end - begin + 1);
}

- 201
- 2
- 2
Use the Native JavaScript Methods: String.trimLeft()
, String.trimRight()
, and String.trim()
.
String.trim()
is supported in IE9+ and all other major browsers:
' Hello '.trim() //-> 'Hello'
String.trimLeft()
and String.trimRight()
are non-standard, but are supported in all major browsers except IE
' Hello '.trimLeft() //-> 'Hello '
' Hello '.trimRight() //-> ' Hello'
IE support is easy with a polyfill however:
if (!''.trimLeft) {
String.prototype.trimLeft = function() {
return this.replace(/^\s+/,'');
};
String.prototype.trimRight = function() {
return this.replace(/\s+$/,'');
};
if (!''.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
}

- 72,308
- 93
- 206
- 262
-
`String.trimLeft()` and `String.trimRight()` are not part of any ECMAScript standard. Plus, your answer is identical to the accepted answer for this question. – Brad Feb 23 '13 at 05:34
-
1@Brad True, but they still have wide browser support. And the polyfill takes care of any inconsistencies. – Web_Designer Feb 23 '13 at 05:37
-
1You should consider deleting your answer. It doesn't add anything that hasn't already been covered 5x over by other answers already here. – Brad Feb 23 '13 at 05:38
-
4
-
1@Brad I prefer the native JavaScript implementation when available. That answer makes up its own `lTrim()` and `rTrim()` methods. – Web_Designer Feb 23 '13 at 05:42
-
Your `trimLeft` and `trimRight` are made up as well. It even says so in the documentation you linked to. – Brad Feb 23 '13 at 05:44
-
1@Brad They are non-standard yet some browsers still support them, so in those browsers there's no need to create a polyfill. – Web_Designer Feb 23 '13 at 05:47
-
1Yes, I understand that. All I'm saying is that your post doesn't add anything to this discussion that wasn't already there. You are more than welcome to leave it if you please. – Brad Feb 23 '13 at 05:48
-
`trimLeft` and `trimRight` are deprecated in favor of `trimStart` and `trimEnd`. – Sebastian Simon Sep 12 '21 at 19:35
String.prototype.trim = String.prototype.trim || function () {
return this.replace(/^\s+|\s+$/g, "");
};
String.prototype.trimLeft = String.prototype.trimLeft || function () {
return this.replace(/^\s+/, "");
};
String.prototype.trimRight = String.prototype.trimRight || function () {
return this.replace(/\s+$/, "");
};
String.prototype.trimFull = String.prototype.trimFull || function () {
return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, " ");
};
Shamelessly stolen from Matt duereg.
Trim code from angular js project
var trim = (function() {
// if a reference is a `String`.
function isString(value){
return typeof value == 'string';
}
// native trim is way faster: http://jsperf.com/angular-trim-test
// but IE doesn't have it... :-(
// TODO: we should move this into IE/ES5 polyfill
if (!String.prototype.trim) {
return function(value) {
return isString(value) ?
value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
};
}
return function(value) {
return isString(value) ? value.trim() : value;
};
})();
and call it as trim(" hello ")

- 4,134
- 1
- 29
- 42
use simply code
var str = " Hello World! ";
alert(str.trim());
Browser support
Feature Chrome Firefox Internet Explorer Opera Safari Edge
Basic support (Yes) 3.5 9 10.5 5 ?
For old browser add prototype
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}

- 6,244
- 1
- 39
- 36
-
best way to explain as compare to others.but modify it little more i mean `replace` function regexp. i did not get it completely. would u like to explain it a little more the regexp part? – muneeb_ahmed Aug 28 '18 at 10:41
Here's a very simple way:
function removeSpaces(string){
return string.split(' ').join('');
}

- 4,685
- 5
- 27
- 64
-
4
-
3This answer is wrong. `trim` should only remove leading and trailing *whitespace* (which includes tabs and other characters). This instead removes all spaces, including ones in the middle. – mbomb007 Feb 13 '18 at 17:56
-
This unexplained answer is incorrect and should be removed. In other words, it is the correct answer to a different question. – mickmackusa Nov 12 '20 at 02:09
I have a lib that uses trim. so solved it by using the following code.
String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };
-
1This is not a good solution. Consider the case where two instances of jQuery are loaded (a common scenario with tags). When the 2nd instance of jQuery loads, it will set it's `.trim()` method equal to the native `String.prototype.trim` which has already been set to `return jQuery.trim(this)`, thus creating a stack overflow. – Brad M Jul 09 '13 at 14:46
I had written this function for trim, when the .trim() function was not available in JS way back in 2008. Some of the older browsers still do not support the .trim() function and i hope this function may help somebody.
TRIM FUNCTION
function trim(str)
{
var startpatt = /^\s/;
var endpatt = /\s$/;
while(str.search(startpatt) == 0)
str = str.substring(1, str.length);
while(str.search(endpatt) == str.length-1)
str = str.substring(0, str.length-1);
return str;
}
Explanation: The function trim() accept a string object and remove any starting and trailing whitespaces (spaces,tabs and newlines) and return the trimmed string. You can use this function to trim form inputs to ensure valid data to be sent.
The function can be called in the following manner as an example.
form.elements[i].value = trim(form.elements[i].value);

- 3,520
- 3
- 19
- 36
You can do it using the plain JavaScript:
function trimString(str, maxLen) {
if (str.length <= maxLen) {
return str;
}
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}
// Let's test it
sentenceOne = "too short";
sentencetwo = "more than the max length";
console.log(trimString(sentenceOne, 15));
console.log(trimString(sentencetwo, 15));

- 31,849
- 12
- 86
- 121
Don't know what bugs can hide here, but I use this:
var some_string_with_extra_spaces=" goes here "
console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])
Or this, if text contain enters:
console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])
Another try:
console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])

- 807
- 9
- 17
-
This technique is dangerous if the text may contain newline characters. It will truncate the string. There are better / more reliable techniques than this one. `"one two\r\nthree".match(/\S.*\S|\S/)[0]` yields: `"one two"` – mickmackusa Nov 12 '20 at 02:31
Here it is in TypeScript:
var trim: (input: string) => string = String.prototype.trim
? ((input: string) : string => {
return (input || "").trim();
})
: ((input: string) : string => {
return (input || "").replace(/^\s+|\s+$/g,"");
})
It will fall back to the regex if the native prototype is not available.

- 3,202
- 1
- 27
- 25
mine uses a single regex to look for cases where trimming is necessary, and uses that regex's results to determine desired substring bounds:
var illmatch= /^(\s*)(?:.*?)(\s*)$/
function strip(me){
var match= illmatch.exec(me)
if(match && (match[1].length || match[2].length)){
me= me.substring(match[1].length, p.length-match[2].length)
}
return me
}
the one design decision that went into this was using a substring to perform the final capture. s/\?:// (make the middle term capturing) and and the replacement fragment becomes:
if(match && (match[1].length || match[3].length)){
me= match[2]
}
there's two performance bets I made in these impls:
does the substring implementation copy the original string's data? if so, in the first, when a string needs to be trimmed there is a double traversal, first in the regex (which may, hopefully be partial), and second in the substring extraction. hopefully a substring implementation only references the original string, so operations like substring can be nearly free. cross fingers
how good is the capture in the regex impl? the middle term, the output value, could potentially be very long. i wasn't ready to bank that all regex impls' capturing wouldn't balk at a couple hundred KB input capture, but i also did not test (too many runtimes, sorry!). the second ALWAYS runs a capture; if your engine can do this without taking a hit, perhaps using some of the above string-roping-techniques, for sure USE IT!

- 1,492
- 13
- 21
For IE9+ and other browsers
function trim(text) {
return (text == null) ? '' : ''.trim.call(text);
}

- 10,951
- 6
- 52
- 65