Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

How to trim spaces between characters of string using javascript  RSS feed

 
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.
 
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
 
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!