Check out this awesome script to remove white spaces:
This script works 100% but…
I have one question how do you join the string with 1 white space between words?
For example if the user typed in 2 or 3 spaces instead of 1 per word.
myString would be myString.text if you were using a text input field instead of defining myString
String.prototype.trim = function ( ) {
// Split the string into an array of characters.
var chars = this.split("");
// Remove any whitespace elements from the beginning of the array using splice( ).
// Use a break statement to exit the loop when you reach a non-whitespace character
// to prevent it from removing whitespace in the middle of the string.
for (var i = 0; i < chars.length; i++) {
if (chars* == "\r" ||
chars* == "
" ||
chars* == "\f" ||
chars* == " " ||
chars* == " ") {
chars.splice(i, 1);
i--;
} else {
break;
}
}
// Loop backward through the array, removing whitespace elements until a
// non-whitespace character is encountered. Then break out of the loop.
for (var i = chars.length - 1; i >= 0; i--) {
if (chars* == "\r" ||
chars* == "
" ||
chars* == "\f" ||
chars* == " " ||
chars* == " ") {
chars.splice(i, 1);
} else {
break;
}
}
// Recreate the string with the join( ) method and return the result.
return chars.join("");
};
// Create a string with beginning and ending whitespace.
myString = "
\r\f a string
";
/* Display the value before calling the trim( ) method. Displays:
this string value is:
a string
<end>
*/
trace("this string value is: " + myString + "<end>");
// Set myString to the value returned by the trim( ) method.
myString = myString.trim( );
/* Now, display the value again using the same trace( ) statement. Displays:
this string value is: a string<end>
*/
trace("this string value is: " + myString + "<end>");