Trim All Spaces in JavaScript
Author
Zhou Renjian
Create@
2005-01-28 16:17
/*
* It will save up to about 8-9%.
*
*/
private static String trimSpaces(String content) {
StringBuffer contentBuffer = new StringBuffer();
int nextIndex = 0;
int markIndex = 0;
int length = content.length();
char ch = '\0';
char prevCh = '\0';
char nextCh = '\0';
boolean isPrevSpace = false;
boolean isPrevMark = false;
for (int i = 0; i < length; i++) {
ch = content.charAt(i);
if (ch == '>' || ch == '<'
|| ch == '{' || ch == '}'
|| ch == '[' || ch == ']'
|| ch == '(' || ch == ')'
|| ch == '=' || ch == ','
|| ch == '+' || ch == '-'
|| ch == '*' || ch == '/'
|| ch == '|' || ch == '&'
|| ch == '!' || ch == ';') {
contentBuffer.append(ch);
isPrevMark = true;
isPrevSpace = false;
} else if (ch == ' ' || ch == '\t') {
isPrevSpace = true;
prevCh = ch;
} else {
if (isPrevSpace && !isPrevMark) {
// fix up
contentBuffer.append(prevCh);
}
isPrevMark = false;
isPrevSpace = false;
contentBuffer.append(ch);
}
}
return contentBuffer.toString();
}