# Removing whitespaces

**URL:** <https://forum.kirupa.com/t/removing-whitespaces/251859>\
**Category:** Uncategorized\
**Created:** [February 13, 2008, 10:13am UTC](https://forum.kirupa.com/t/removing-whitespaces/251859 "2008-02-13T10:13:07Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![flash\_noob1](https://avatars.discourse-cdn.com/v4/letter/f/8e7dd6/32.png) [@flash\_noob1](https://forum.kirupa.com/u/flash_noob1)\
**Post date:** [February 13, 2008, 10:13am UTC](https://forum.kirupa.com/t/removing-whitespaces/251859/1 "2008-02-13T10:13:07Z")

</div>

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

```auto

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>");

```
