Trim string in JavaScript
It’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: stackoverflow.com/a/8522376/8432
To 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 ‘) .
20 Answers 20
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:
That said, if using jQuery , $.trim(str) is also available and handles undefined/null.
String.prototype.trim=function(); String.prototype.ltrim=function(); String.prototype.rtrim=function(); String.prototype.fulltrim=function();
The trim from jQuery is convenient if you are already using that framework.
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? 🙂
this only trims whitespace (newline) .. it does not work like php trim , where you can trim characters as well
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.
Added natively in: JavaScript 1.8.1 / ECMAScript 5
Firefox: 3.5+
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"
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();
If you are using jQuery, use the jQuery.trim() function. For example:
if( jQuery.trim(StringVariable) == '')
Flagrant Badassery has 11 different trims with benchmark information:
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 while (end > begin && str.charCodeAt(end) < 33) < --end; >return str.substr(begin, end - begin + 1); >
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, ''); >; > >
@Brad True, but they still have wide browser support. And the polyfill takes care of any inconsistencies.
You should consider deleting your answer. It doesn’t add anything that hasn’t already been covered 5x over by other answers already here.
@Brad I prefer the native JavaScript implementation when available. That answer makes up its own lTrim() and rTrim() methods.
@Brad They are non-standard yet some browsers still support them, so in those browsers there’s no need to create a polyfill.
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, " "); >;
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 «)
var str = " Hello World! "; alert(str.trim());
Feature Chrome Firefox Internet Explorer Opera Safari Edge Basic support (Yes) 3.5 9 10.5 5 ?
For old browser add prototype
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?
function removeSpaces(string)
This 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.
This unexplained answer is incorrect and should be removed. In other words, it is the correct answer to a different question.
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); >;
This 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.
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
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);
String.prototype.trim()
The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string.
To return a new string with whitespace trimmed from just one end, use trimStart() or trimEnd() .
Try it
Syntax
Return value
A new string representing str stripped of whitespace from both its beginning and end. Whitespace is defined as white space characters plus line terminators.
If neither the beginning or end of str has any whitespace, a new string is still returned (essentially a copy of str ).
Examples
Using trim()
The following example trims whitespace from both ends of str .
const str = " foo "; console.log(str.trim()); // 'foo'
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Mar 26, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Trim spaces from start and end of string
I am trying to find a way to trim spaces from the start and end of the title string. I was using this, but it doesn’t seem to be working:
var s = ‘ 1 ‘; s = s.replace(/^\s+|\s+$/g, »); alert(‘-‘ + s + ‘-‘); // it works like this, you dont need the parens or square braces.
Javascript has .trim built in now, so this is answer for modern browsers: stackoverflow.com/a/3000900/29182
15 Answers 15
Note: As of 2015, all major browsers (including IE>=9) support String.prototype.trim(). This means that for most use cases simply doing str.trim() is the best way of achieving what the question asks.
Steven Levithan analyzed many different implementation of trim in Javascript in terms of performance.
for «general-purpose implementation which is fast cross-browser», and
function trim11 (str) < str = str.replace(/^\s+/, ''); for (var i = str.length - 1; i >= 0; i--) < if (/\S/.test(str.charAt(i))) < str = str.substring(0, i + 1); break; >> return str; >
«if you want to handle long strings exceptionally fast in all browsers».
References
The new Safari (5), Chrome(5), Firefox(3.6) and Opera (10.5) all support a native String trim method. That being the case, I’d assign a method to String.prototype, if it does not exist, rather than a new global function.
I doubt that after recent improvements on javascript performance this test is still relevant or reliable as it was at the time of this answer.
If using jQuery is an option:
/** * Trim the site input[type=text] fields globally by removing any whitespace from the * beginning and end of a string on input .blur() */ $('input[type=text]').blur(function()< $(this).val($.trim($(this).val())); >);
As @ChaosPandion mentioned, the String.prototype.trim method has been introduced into the ECMAScript 5th Edition Specification, some implementations already include this method, so the best way is to detect the native implementation and declare it only if it’s not available:
if (typeof String.prototype.trim != 'function') < // detect native implementation String.prototype.trim = function () < return this.replace(/^\s+/, '').replace(/\s+$/, ''); >; >
I’m always a little bemused by this meme of checking if the property is a function. If it’s not a function is the right behavior really to overwrite it? Perhaps you should throw an error in that case.
@kojiro, well, maybe throwing an error would be good, but I see it like this: I’m trying to make an spec-compliant shim, and if String.prototype.trim is not a function, it is not the String.prototype.trim method described on the ECMAScript 5th Edition Specification, the spec guarantees that trim is a function object on ES5 environments.
I know this is an old post, but just thought I’d share our solution. In the quest for shortest code (doesn’t everyone just love terse regex), one could instead use:
BTW: I ran this same test through the link shared above blog.stevenlevithan.com — Faster JavaScript Trim and this pattern beat all the other HANDS down!
Using IE8, added test as test13. The results were:
Original length: 226002
trim1: 110ms (length: 225994)
trim2: 79ms (length: 225994)
trim3: 172ms (length: 225994)
trim4: 203ms (length:225994)
trim5: 172ms (length: 225994)
trim6: 312ms (length: 225994)
trim7: 203ms (length: 225994)
trim8: 47ms (length: 225994)
trim9: 453ms (length: 225994)
trim10: 15ms (length: 225994)
trim11: 16ms (length: 225994)
trim12: 31ms (length: 225994)
trim13: 0ms (length: 226002)