This is a discussion on Trimming strings in JavaScript within the HTML, CSS and Javascript Coding Techniques forums, part of the Web Development category; Hi all.... Trimming strings in JavaScript Thanks & Regards Pvinoth....
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Hi... If you've worked with other C-based languages, like C, C++ or C#, you'll know that there's a very handy function called trim() which is able to automatically remove leading and trailing spaces from the string. Unfortunately, this function has been left out of JavaScript. However, you can easily make your own string trimming function, as shown below: function strtrim(string) { //Remove leading spaces while(string.charAt(0) == " ") string = string.substring(1, string.length); //Remove trailing spaces while(string.charAt(string.length-1) == " ") string = string.substring(string, string.length-1); return string; } Then, to trim a string, simply use: myString = strtrim(myString); A better way to implement this function is to acutally add it to the string object, so the syntax is myString.trim() rather than strtrim(myString): String.prototype.trim = function() { var string = this; //Remove leading spaces while(string.charAt(0) == " ") string = string.substring(1, string.length); //Remove trailing spaces while(string.charAt(string.length-1) == " ") string = string.substring(string, string.length-1); return string; } thnx.... |
| |||
| function trimAll(sString) { while (sString.substring(0,1) == ' ') { sString = sString.substring(1, sString.length); } while (sString.substring(sString.length-1, sString.length) == ' ') { sString = sString.substring(0,sString.length-1); } return sString; } |
![]() |
| Thread Tools | |
| Display Modes | |
| |
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| How to concatenate strings with Perl? | amansundar | Perl | 3 | 11-28-2007 09:39 PM |
| How does JavaScript Reporter differ from JavaScript editors? | Pvinothkumar | HTML, CSS and Javascript Coding Techniques | 1 | 09-13-2007 05:59 AM |
| Connection Strings Info | Gopisoft | VB.NET Programming | 0 | 07-17-2007 05:42 AM |