Return to Kroll Design home page

JavaScript Tutorials

 
« Return

remove blanks from strings

Use the charAt method and concatenation ("+") in a loop to remove all blank spaces from a string.

Code:

<script type="text/javascript">
//<![CDATA[
var myArray = new Array(
"test 1",
"another test",
"noblanks",
"last test");

function removeBlanks(myString)
{
  var outString = "";
  for (myChar=0; myChar<myString.length; myChar++)
  {
  if (myString.charAt(myChar) != " ")
    { outString = outString + myString.charAt(myChar); }
  }
  return outString;
}

myString = "test 1";
document.write("before: ", myString, "<br>");
document.write("after: ", removeBlanks(myString), "<br><br>");

myString = "a b c def g h";
document.write("before: ", myString, "<br>");
document.write("after: ", removeBlanks(myString), "<br><br>");

myString = "  1 2 3     ";
document.write("before: ", myString, "<br>");
document.write("after: ", removeBlanks(myString), "<br><br>");

for (i=0; i<myArray.length; i++)
{
  document.write("before: ", myArray[i], "<br>");
  document.write("after: ", removeBlanks(myArray[i]), "<br><br>");
}
//]]>
</script>

Output:



 
« Return


©2012 Kroll Design    info@KrollDesign.net    781.910.3694
Last modified: 12/31/1969 7:00 PM