[an error occurred while processing this directive]

JavaScript Remove Spaces

                          

In this section, yow will learn how to remove spaces from the string.

To remove the spaces, we have simply used JavaScript methods split() and join(). Now to use these methods, we have defined a string. Firstly the split(" ") method splits the string into an array of strings. It takes the string argument, therefore the method enclosed a pair of double quotes which allow the string to be split. Then the method join("") join all the elements of an array into a string. As this method contains a parameter 'separator' which adds all array elements by placing the separator between them. In our example, to make the original string spaces less, first we split the original string by spaces using split(' ') and then join all elements with no space string using join('').

Here is the code:

<html>
<h2>JavaScript Remove Spaces</h2>
<script language="javascript" type="text/javascript">
var string="All glitters are not gold";
var newString=string.split(' ').join('');
document.write("The original string is = "+string+"<br>");
document.write("After removing the spaces, the string becomes = "+newString);
</script>
</html>

Output will be displayed as:

Download Source Code:

                          

[an error occurred while processing this directive]