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.
This is the perfect trim function for JavaScript.
its pretty cool.. you helped me solve a big problem with my codes. Thanks!
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
I am looking for a trim function that deals with Non-Ascii characters. Basically, I am doing some validation on browser using JavaScript
Fantastic. thank you
Perfect. Just what I needed. Thank you!
Fantastic, I like the prototype version. You saved me alot of time.
the best trim i have seen! thnx! could someone please explain how it works? cheers k
@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.
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.
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"
Hi Tyler - this function should remove multiple whitespaces. Do you have example?
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.
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; }
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;-)
bugger, heh, above is not correct, this is though:
String.prototype.trim = function() { var _ret = this.replace(/^\s+|\s+$/g, ''); return _ret.replace(/^(\ \;)+|(\ \;)+$/g, ''); }
;-)
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, '') ;
Very useful, cheers!
Thanks a lot for this. Very helpful.
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?
Thanks a lot! This is by far the best javascript trim i've encountered.
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
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!
Duh.
Way to early. :-)
I can just strip all white space with...
/\s/g,
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.
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, ''); }
Lovely Script pal :) Keep up the good work
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
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.......
kvz, thanks ur code was useful
Can also implement it as a prototype. Have a look at http://whadiz.com/c/whatis.aspx/programming/javascript/javascript_trim
Thanks. It is simple, clean and works!
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.
There's a good comparison of different approaches on trimming strings in javascript here: http://blog.stevenlevithan.com/archives/faster-trim-javascript
Excellent work. Just what I was looking for - a compact regexp thats works and hasn't given me brain failure trying to understand it!
Hi!! a zillion thanks for this help in javascript.
Please let me kn if there any other way other than RSS/Atom to stay in touch with your website?
Strip all white space in string?
String.prototype.str_replace = function (needle, str) {return this.split(needle).join(str)}
" sha un web st er ".str_replace(" ", "")
--> "shaunwebster"
Of course with this on you could strip any character.. Dunno if it's faster then regexp
Thanks. Was a big help.
This is my trim function without the overhead of regular expressions.
function trimstr(str) { var whitespace= " \n\r\t\f";
for( var i= 0; i = i; j-- ) if( whitespace.indexOf( str.charAt(j) )
Thanks that helped me
Thanks !!! this what the code that I was looking for...
Tom,
Can you help me to understand how your function is working? I am new to Javascript, so not able to understand the logic.
function trimstr(str) { var whitespace= " \n\r\t\f";
for( var i= 0; i = i; j-- ) if( whitespace.indexOf( str.charAt(j) )
Thanks.
thanks
thanks for the tip
excellent, works like a charm, cheers
hmmm its sloved a big big problem for me. thnx for the author
the "perfect trim function for javascript" didn't get rid of a string i'm grabbing from my webpage.
so i added in the \t (tab), \n (newline) and ' ' (whitespace) and solved my problem
var trimmed = thisH2.innerHTML.replace(/^\s+|\t+|\n+| |\s+$/g, '') ;
Comments