Replacing Multiple Spaces with Single Space using JavaScript Replace () Function


string.replace(searchvalue, newvalue)

Definition and Usage

In the Replace() method, the string for a specified value is searched for a regular expression and a new string is returned where the specific values are replaced.

Multiple spaces can be a problem for JavaScript developers, ASP.NET, T-SQL and VB.NET developers. Here JavaScript Replace() cites two arguments:

  • The First argument is related to the string that is to be replaced using JavaScript Replace function.
  • The Second argument is for the new replaced string.

Here is an example of JavaScript Replace() where multiple spaces are shown to be removed with a single space:


<script type="text/javascript">

    var myStr = 'PHP     CSS   HTML  jQuery';

    alert(myStr);  // Output 'PHP     CSS   HTML  jQuery'


    var newStr = myStr.replace(/  +/g, ' ');

    alert(newStr);  // Output 'PHP CSS HTML jQuery'


The developers need to keep one thing in mind that while printing the strings on the web page, the difference will not be visible. The browsers treat multiple spaces as a single space until the developers preserve the white space.

In the above example, the new string is returned that provides the Output of single space. Here, to perform the global search and replace() method, the ‘g’ switch can be included in a regular expression. However, in case, the first parameter here is a string as shown above then developers must include ‘g’ switch in the flags parameter.

Moreover, here in the example of replacing multiple spaces into single space, the string method is used. The Replace() searches for the match between a string and a regular expression that acts as a tool and the output is given as a new string. In the above Output, this function has helped to remove leading spaces that removed multiple spaces and merged into a single space.

The JavaScript Replace() function helps in unifying the spaces and reduces a number of white spaces that occurs while writing the script. For replacing all the occurrences of multiple spaces, the use of ‘g’ or a global modifier in the string method should be used.

View Demo

Leave a Reply

Your email address will not be published. Required fields are marked *