| 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: 15357
|
|
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
|
 |
 |
|
|
subject: How to trim spaces between characters of string using javascript
|
|
|