How To trim() in Javascript
By Angsuman Chakraborty, Gaea News NetworkFriday, March 17, 2006
Javascript doesn’t natively support trim on strings. It is however very easy to implement with regular expressions.
<script language="javascript"> function trim (str) { str = this != window? this : str; return str.replace(/^\s+/, '').replace(/\s+$/, ''); } // Test if(trim(" \t \n test ram \r\n \t \t\n") == "test ram") alert("Yes"); </script>
December 30, 2009: 8:36 pm
‘ hi there ‘.replace(/(^\s+|\s+$)/g, ”); // eg: paste the following into your browser address bar and hit go … javascript: alert(’>’ + ‘ hi there ‘.replace(/(^\s+|\s+$)/g, ”) + ‘<’); // the /(^\s+|\s+$)/g basically says: matchstart followed by space or match end preceded by space globally. perl re is the best! // rgds, e |
![]() jatin |
September 9, 2009: 12:42 am
form.id.value.replace(/\s/g, “”); |
![]() noname |
April 25, 2008: 2:16 am
Can also implement a trim function by extending the string type using a prototype. Have a look at https://whadiz.com/c/whatis.aspx/programming/javascript/javascript_trim |
![]() chandra prakash |
![]() chandra prakash |
March 31, 2008: 4:40 am
To answer this.. Javascript and Jscript are the same meaning with the different versioning. Jscript is the version of Microsoft javascript. Some time the Document Object Model might differ from the Javascript. And Jscript works only on IE browser. This might answer your question. Thanks for the trim code. Thanks. |
![]() Rahul Chouhan |
December 5, 2007: 12:42 am
function trim(str, chars) { function ltrim(str, chars) { function rtrim(str, chars) { |
![]() UKC |
November 15, 2007: 5:57 am
This should actually be as follows: surname = surname.replace(/^\s+/, “”).replace(/\s+$/, “”); |
![]() joseph |
![]() R.Kapiljith |
July 18, 2007: 1:19 pm
// This function is for stripping leading and trailing spacesfunction trim(str) { if (str != null) { var i; for (i=0; i=0; i–) { if (str.charAt(i)!=” “) { str=str.substring(0,i+1); break; } } if (str.charAt(0)==” “) { return “”; } else { return str; } }} |
February 9, 2007: 2:46 am
uday plese try to understand yarr, why ur try to javascruipt go to your bad and just sleeping yarr, edighot |
![]() Uday |
![]() Uday |
January 20, 2007: 12:35 am
Hi.. im new to javascript… first of all i want to know whether javascript and jscript is same.. or any other difference… and plz guide me what is the use of trim function… |
Naveen R