SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software
Javascript Tutorials and Javascript Frameworks jQuery resources, tools, articles, code samples and downloads for Web Programmers


Use Javascript Replace Function Example to Replace Multi Space in a String with Single Space


In this Javascript tutorial, web developers will find an example Javascript code that they can use in order to replace and remove multiple spaces with single space character in a given text or string variable.
Multi space characters in text and string variables can be a big problem not only for Javascript developers but also in VB.NET, ASP.NET, T-SQL or in all other programming languages.

Javascript String REPLACE function has two arguments.
The first argument or the first parameter used in Javascript Replace function is string to be replaced.
The second argument is the new replace string.
For more detailed information String Replace function, please refer to Javascript Replace Function and String Replace Method.

In this Javascript Replace function example, we will remove the redundant multi space characters in the string variable text :
"Replace     multiple  spaces with single    space      using javascript replace function"





Here is the variable declarations part of our Javascript Replace function example code.
Note that there exist multi space characters between words in out example Javascript string variable.

<script type="text/javascript" type="text/javascript">
var string_variable;
string_variable = "Replace     multiple  spaces with single    space      using javascript replace function";
alert(string_variable);
</script>
Code

string-functions-javascript-replace-function-example

Now, we will search for two spaces next to eacj other as " " in the javascript string variable.
If we can find at least one, we will replace two adjacent space characters with single space character in a Javascript While loop.
Let's build the While Loop in Javascript code and replace and remove multiple spaces with one space in a recursive method.

<script type="text/javascript" type="text/javascript">
var string_variable;
string_variable = "Replace     multiple  spaces with single    space      using javascript replace function";
alert(string_variable);

var intIndexOfMatch = string_variable.indexOf("  ");

while (intIndexOfMatch != -1){
  string_variable = string_variable.replace( "  ", " " )
  intIndexOfMatch = string_variable.indexOf( "  " );
}

alert(string_variable);
</script>
Code

Here is the output of our example Javascript Replace function in string.

javascript-replace-function-in-string

As you can see, the Javascript string replace function we code, remove multiple spaces with single space character.



Javascript


Copyright © 2004 - 2021 Eralper YILMAZ. All rights reserved.