File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes HTML, CSS and JavaScript and the fly likes How to trim spaces between characters of string using javascript Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "How to trim spaces between characters of string using javascript " Watch "How to trim spaces between characters of string using javascript " New topic
Author

How to trim spaces between characters of string using javascript

Shrikanth Nekkanti
Ranch Hand

Joined: Jul 12, 2007
Posts: 48
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

Joined: Nov 08, 2001
Posts: 15376
    
    6
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

Joined: Aug 26, 2001
Posts: 7610
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


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
wood burning stoves
 
subject: How to trim spaces between characters of string using javascript
 
Similar Threads
Remove unwanted chars (new line,tab) in java
How to remove spaces
Stirng replacement seemingly simple but I couldnt find a simple way
trim( ) method
remove white spaces