Trim a string in JavaScript
01 July 2006 - JavaScript
I've seen all kinds of techniques used to trim a string in JavaScript, some of them a bit bonkers. Here's the 'right' way:
var trimmed = str.replace(/^\s+|\s+$/g, '') ;
So there.
No more fat.
01 July 2006 - JavaScript
I've seen all kinds of techniques used to trim a string in JavaScript, some of them a bit bonkers. Here's the 'right' way:
var trimmed = str.replace(/^\s+|\s+$/g, '') ;
So there.
Comments
sohnee - 11 August 2006 08:12
This is the perfect trim function for JavaScript.
persisjas - 16 October 2006 07:59
its pretty cool.. you helped me solve a big problem with my codes. Thanks!
leo costela - 17 April 2007 14:59
To make things even more interesting we could add this to the String class:
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }
Cheers
Radmeister - 26 April 2007 22:23
I am looking for a trim function that deals with Non-Ascii characters. Basically, I am doing some validation on browser using JavaScript
Tani - 02 May 2007 06:13
Fantastic. thank you
Peter - 16 May 2007 19:21
Perfect. Just what I needed. Thank you!
Shawn - 24 May 2007 02:18
Fantastic, I like the prototype version. You saved me alot of time.
karl - 26 June 2007 17:58
the best trim i have seen! thnx! could someone please explain how it works? cheers k
snotigr - 27 June 2007 14:36
@karl...
The replace function uses a regular expression to replace anything that matches with the expression with the second argument, in this case '', an empty string (nothing).
The first argument, the regular expression, says:
/^\s+|\s+$/g
This means: / =start the regular expression
^ =match the START of the line and then... \s =match spaces + =one or more of them
| =OR (think of this as ALSO)
\s =match spaces + =one or more of them... $ =to the END of the line
/ =end of the regular expression
g =GLOBAL (do this for EVERY MATCHING CASE) this will cause the expression to match the start, and then go on to the end. Otherwise it would quit after the first match (the start of the line).
So it's saying, find one ore more spaces at the start of the line, also one or more spaces at the end of a line, and replace them with '' that is, an empty string, or nothing.
For a really good tutorial (if you're up for it) see: http://www.regular-expressions.info/ this guy really knows his stuff.
Tyler - 28 June 2007 02:24
The problem with this function is that it does not remove MULTIPLE whitespaces at either end. A true trim function should remove any whitespace on either end of the string.
elurin - 28 June 2007 14:52 - Visit >
i am not a javascript expert but i thing it is doing well with multiple spaces at both ends.
>>" \n rty \t \t \n ".replace(/^\s+|\s+$/g, ''); >>"rty"
Nick Nettleton - 02 July 2007 17:34
Hi Tyler - this function should remove multiple whitespaces. Do you have example?
bob - 10 July 2007 10:22
String.prototype.trim = function() { return this.replace(/^[\s\u3000]+|[\s\u3000]+$/g, ''); }
This will trim IDEOGRAPHIC SPACE (double byte space) as well as whatever is defined as whitespace for \s. I use this when working with Japanese. If there was some other character you wanted to trim then you could add it in as well.
Here is a list of possible space characters: UNICODE NAME -------------------------------------------------- 0020 SPACE 00A0 NO-BREAK SPACE 1361 ETHIOPIC WORDSPACE 1680 OGHAM SPACE MARK 2002 EN SPACE 2003 EM SPACE 2004 THREE-PER-EM SPACE 2005 FOUR-PER-EM SPACE 2006 SIX-PER-EM SPACE 2007 FIGURE SPACE 2008 PUNCTUATION SPACE 2009 THIN SPACE 200A HAIR SPACE 200B ZERO WIDTH SPACE 202F NARROW NO-BREAK SPACE 205F MEDIUM MATHEMATICAL SPACE 2408 SYMBOL FOR BACKSPACE 2420 SYMBOL FOR SPACE 3000 IDEOGRAPHIC SPACE 303F IDEOGRAPHIC HALF FILL SPACE
Maybe this is what Radmeister was looking for.
mishelangelo - 03 August 2007 15:19
in the same light... here's a quick isNumeric function... you showed me the light
function isNumeric(str){ str=str.replace(/^\s+|\s+$/g, '') ;
if((str.length == 1 && str.match(/^\d+$/g)) || ((str.length > 1) && str.match(/^[-]{0,1}\d*[.]{0,1}\d*$/g))) return true;
return false; }
Tim - 22 August 2007 11:09
I need to also strip out characters from the start and end. I modified this code to:
String.prototype.trim = function() { var _ret = this.replace(/^\s+|\s+$/g, ''); return this.replace(/^(\ \;)+|(\ \;)+$/g, ''); }
I hope I've managed to encode all the characters in that properly;-)
Tim - 22 August 2007 11:12
bugger, heh, above is not correct, this is though:
String.prototype.trim = function() { var _ret = this.replace(/^\s+|\s+$/g, ''); return _ret.replace(/^(\ \;)+|(\ \;)+$/g, ''); }
;-)
blake - 22 August 2007 23:47
im dealing with out put from a legacy app, when a portion of the input string on the input feild was never modified, it will substitute '_' in stead of spaces, or leaving the last portion of the string blank. like this " BEACHES #140000001_____________" this is pretty much its way of saying that no char was input for this point in the string. you trimming code, sligtly modified is what i needed to fix this str.replace(/^[\s_]+|[\s_]+$/g, '') ;
Tom - 12 September 2007 11:12
Very useful, cheers!
Boris - 08 October 2007 19:35
Thanks a lot for this. Very helpful.
Douglas Osborne - 14 November 2007 15:48 - Visit >
What would be the usage?
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }
function WholeName() { var First = document.forms('Form1').elements('txtIndvFirstName').value; var Last = document.forms('Form1').elements('txtIndvLastName').value return Last.trim() + ', ' + First.trim() }
Is this correct?
Arian Reyes - 14 November 2007 17:00
Thanks a lot! This is by far the best javascript trim i've encountered.
Michael O'Neal - 19 November 2007 23:36
The following was a culmination of much aggravation posted to the Google Mashup Editor discussion at: http://groups.google.com/group/google-mashup-editor/topics
To Jason, one of the Google folks I posted the following:
Thank you very much Jason.
I beat myself up for three days trying every permutation and combination I could think of trying to get this to work. The link you gave me:
http://www.nicknettleton.com/zine/javascript/trim-a-string-in-javascript
worked great.
For others, the salient info from this link is:
Trim a string in JavaScript
I've seen all kinds of techniques used to trim a string in JavaScript, some of them a bit bonkers. Here's the 'right' way:
var trimmed = str.replace(/^\s+|\s+$/g, '') ;
I would strongly suggest that those interested visit the site as it has information regarding how this works which should be of interest to those wishing to learn about regular expressions.
Thanks again to Jason and nicknettleton.com, Michael
Shaun - 28 November 2007 16:47
Hey great strip.
How about stripping whitespace inside the string all at the same time?
e.g.
" sha un web st er " = "shaunwebster"
Any help would be great. thanks!
Shaun - 28 November 2007 20:13
Duh.
Way to early. :-)
I can just strip all white space with...
/\s/g,
jaccho’s » javascript的trim方法 - 12 December 2007 01:06 - Visit >
[...] 用到trim了,发现js下并没有提供这个函数。。。囧google下~找到这个 var trimmed = str.replace(/^\s+|\s+$/g, ”) ; [...]
Steve - 17 December 2007 09:07 - Visit >
I've posted a comparison of numerous JavaScript trim implementations here: JavaScript Trim. The method shown here is not bad, but it could be faster.
kvz - 08 January 2008 12:53 - Visit >
A collection of PHP functions Ported to Javascript is being worked on here: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_wordwrap/
Currently there are 27 PHP equivalents, including the following trim() function:
function trim( str ) { // http://kevin.vanzonneveld.net // + improved by: mdsjack (http://www.mdsjack.bo.it) // + improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
return str.replace(/(^[\s\xA0]+|[\s\xA0]+$)/g, ''); }
Nripin Babu - 19 February 2008 09:56
Lovely Script pal :) Keep up the good work
trim in Javascript! « Nisshobdo Rati - 19 February 2008 10:51 - Visit >
[...] Thanks to nicknettleton! [...]
appaji - 21 February 2008 12:42
it works fine. you save couple of hours for me. it's an excellent solution really great. every body should congratulate you.. bye for now
aswath - 25 March 2008 06:54
i used the below code.... var str = " blah blah "; var trimmed = str.replace(/^\s+|\s+$/g, '') ; alert(trimmed); alert(trimmed.value.length);
its aint workn.. any help.......
angelben - 01 April 2008 10:47
kvz, thanks ur code was useful
Riaan - 25 April 2008 09:10 - Visit >
Can also implement it as a prototype. Have a look at http://whadiz.com/c/whatis.aspx/programming/javascript/javascript_trim
Bin Hu - 30 June 2008 18:48
Thanks. It is simple, clean and works!
Sonal - 14 July 2008 13:04
When i use a single qoute in my search after using this (/^\s+|\s+$/g|\', ''), it breaks the search:
function SearchQuery() { var test=document.getElementById('search_keyword'); var trimmed=test.value.replace(/^\s+|\s+$/g|\', '');
if(test.value=="type words"|| trimmed=="") { alert('Please enter text in the Search box'); return false; }else{return true;} }
it breaks the code for example: search for O'Reilly....and it breaks.