Entry
How can I trim (remove leading and trainling withespace from) a string?
how to remove spaces in javascript
May 12th, 2008 20:34
i can do it, Taksh Verdhan, Martin Honnen, Vijay Solanki,
Use regular expressions to remove the white space
function trimString (str) {
str = this != window? this : str;
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
Then you can call
var s = ' Kibo ';
s = trimString(s);
alert(s.length);
The above function is set up so that it can be added as a method to the
String.prototype:
function trimString (str) {
str = this != window? this : str;
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
String.prototype.trim = trimString;
which you can then call as follows:
var s = ' Kibo ';
s = s.trim();
alert(s.length);
Decide for yourself which way you find more elegant.
Note that this whole solution using regular expressions is JavaScript
1.2 so will not work with version pre 4 browsers.
So here is a function for NN2 and NN3 and IE3 which removes leading and
trailing spaces from a string:
function trimString (str) {
while (str.charAt(0) == ' ')
str = str.substring(1);
while (str.charAt(str.length - 1) == ' ')
str = str.substring(0, str.length - 1);
return str;
}
//Example
var s = ' Kibo ';
s = trimString(s);
alert(s.length)
Note that contrary to the regular expression version only spaces but
not all whitespace (e.g. tabs linefeeds) are removed but you could
adapt the function to do that as well.
http://linkexchange-7.blogspot.com/
http://eroticreview.blogspot.com/
http://friendsreuniteddating.blogspot.com/
http://romaniandating.blogspot.com/
http://myspaceadvertising.blogspot.com/
http://newofficefurniture.blogspot.com/
http://web20box.blogspot.com/
http://carautoaccessories.blogspot.com/
http://sainisamaj.blogspot.com/
http://beyonceknowleshotphoto.blogspot.com/
http://linkexchange7.blogspot.com/
http://beyonceknowlesphoto.blogspot.com/
http://viewsat.blogspot.com/
http://paiddirectoy.mylinea.com/
http://linkchannel.mylinea.com/
http://businessdirs.mylinea.com/
http://allwebdirectory.mylinea.com/
http://seopdir.mylinea.com/
http://automotivedir.mylinea.com/
http://myspacedirectoy.mylinea.com/
http://www.stupidarticles.com
http://www.halazona.com
http://www.shikapika.com
http://www.stakoza.com
http://www.uploadarticles.com
http://www.ganazat.com
http://www.damima.com
http://www.tarabiza.com
http://www.articlesxarticles.com
http://www.articlesfreedirectory.com