Skip to content
Home » How to Remove Spaces From a String in JavaScript

How to Remove Spaces From a String in JavaScript

In this tutorial let’s learn about How to Remove Spaces From a String in JavaScript. JavaScript includes a String class that is available globally. It includes a multiple of helpful string transformation functions.

In order to Remove Spaces From a String in JavaScript use any one of the below approaches.

  1. Use replace() to Only Remove White Space from a String in JavaScript
  2. Using split() and join() Methods to Remove Spaces From a String in JavaScript
  3. Use trim() to Remove Spaces from a String using JavaScript

Remove Spaces From a String using replace() in JavaScript

The replace() method is used to replace one string with another. It requires two parameters, the first of which is the string to be replaced and the second of which is the string to be replaced with. The second string can be specified as an empty string to replace the empty space.

Syntax for str.replace():

string.replace(/ /g, “”)

Along with the global property, the first parameter is given a regular expression with a space character (” “). This will select every instance of a space in the text, which may then be eliminated by passing an empty string as the second parameter. This removes all of the spaces from the original string.

Code Example:

<!DOCTYPE html>
<html>

<head>
	<title>
		How to remove spaces from
		a string using JavaScript?
	</title>
</head>

<body>
	<h1 style="color: darkblue">
		Similar Geeks
	</h1>
	
	<p>
		Original string :
		Similar   Geeks     Website
	</p>
	
	<p>
		New String :
		<span class="output"></span>
	</p>
	
	<button onclick="removeSpaces()">
		Remove Spaces
	</button>
	
	<script type="text/javascript">
		function removeSpaces() {
			originalText =
				"Similar   Geeks     Website";
		
			newText =
				originalText.replace(/ /g, "");
		
			document.querySelector('.output').textContent
					= newText;
		}
	</script>
</body>

</html>

Output :

How to Remove Spaces From a String in JavaScript

Remove Spaces From a String using split() and join() Methods in JavaScript

The split() method divides a text into numerous substrings and returns them as an array. A separator can be given as a parameter, and the string will be divided whenever that separator is found. This option specifies the space character (” “) to split the string whenever a space occurs.

Syntax:

string.split(” “).join(“”)

The join() method joins an array of strings using a separator. This will return a new string containing the connected string separated by the provided separator. This method is applied to the returned array without the usage of a separator (“”) to unite the strings. This function joins the strings in the array and returns a new string. This removes all of the spaces from the original string.

Code Example:

<!DOCTYPE html>
<html>

<head>
	<title>
		How to remove spaces from
		a string using JavaScript?
	</title>
</head>

<body>
	<h1 style="color: darkblue">
		Similar Geeks
	</h1>
	
	<p>
		Original string :
		Similar   Geeks  Website
	</p>
	
	<p>
		New String :
		<span class="output"></span>
	</p>
	
	<button onclick="removeSpaces()">
		Remove Spaces
	</button>
	
	<script type="text/javascript">
    function removeSpaces() {
        originalText = 
            "Similar   Geeks    Website";
      
        removedSpacesText = 
            originalText.split(" ").join("");
      
        document.querySelector('.output').textContent
                = removedSpacesText;
    }
</script>
</body>

</html>

Output :

How to Remove Spaces From a String in JavaScript

Remove All the Spaces From a String using replace()

Any whitespace sign, such as spaces, tabs, and line breaks, is referred to by the regular expression pattern \s.

Here’s a quick rundown of what the regular expression does:

  • \s: corresponds to any whitespace symbol, including spaces, tabs, and line breaks.
  • +: correspond to one or more of the preceding tokens (referencing \s)
  • g: the g at the end denotes iterative searching across the entire string.

Syntax:

string.replace(/\s+/g, ”)

JavaScript code :

<script type="text/javascript"> 
    const removeSpaces = () => { 
        let text1 =  
            "Similar Geeks Python"; 

        let text2 =  
            text1.replace(/\s+/g, ''); 

        document.querySelector('.output').textContent 
            = text2; 
    } 
</script> 

HTML and JavaScript Code:

<!DOCTYPE html>
<html>

<head>
	<title>
		How to remove spaces from
		a string using JavaScript?
	</title>
</head>

<body>
	<h1 style="color: darkblue">
		Similar Geeks
	</h1>
	
	<p>
		Original string :
		Similar   Geeks  Python
	</p>
	
	<p>
		New String :
		<span class="output"></span>
	</p>
	
	<button onclick="removeSpaces()">
		Remove Spaces
	</button>
	
	<script type="text/javascript"> 
    const removeSpaces = () => { 
        let text1 =  
            "Similar Geeks Python"; 

        let text2 =  
            text1.replace(/\s+/g, ''); 

        document.querySelector('.output').textContent 
            = text2; 
    } 
</script> 
</body>

</html>

Output :

Remove All the Spaces From a String using replace() in JavaScript

Conclusion

In this tutorial we discussed different approaches like using replace(), split() and join(). Each method has their own limitations but using regular expressions tends to be works faster.

Similar Posts:

How to Generate Random String using JavaScript
How to Convert a String to Boolean in JavaScript