Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to trim spaces between characters of string using javascript

 
Shrikanth Nekkanti
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a function trim(str) which is trimming spaces at begining and after end of string . how to make it to trim spaces between characters of string.
 
Eric Pascarello
author
Rancher
Posts: 15385
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Something like



Would call it like this



I just wrote all that code here, so hopefully there is no typos.

Eric
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For trimAll, I would take special care if the function is applied on a string that contains HTML tags, because the space(s) between attribute values are going to be removed.

Example:
"<table border='0' class='myTable'>".trimAll();
would yield
<tableborder='0'class='myTable'>
which is not good.

Instead, I would declare trimAll as follows:
String.prototype.trimAll = function(replaceStr) {
return this.replace(/\s+/g,replaceStr || "");
}

That way, if replaceStr is provided, the spaces will be replaced by it otherwise, the empty string is used by default.

Now,
"<table border='0' class='myTable'>".trimAll(" ");
correctly yields
<table border='0' class='myTable'>

Of course, if you have left and/or right spaces, you'd have to left/right-trim them as well
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic