How do I remove whitespace from a string in JavaScript?
Antek N
antek n profile pic

To remove whitespace from a string in JavaScript, you can use various methods and techniques. Here's a step-by-step guide on how to achieve this: 1. Create a string that contains whitespace:

1
2
3

   const str = "  Hello,   World!  ";
   

2. Use thetrim() method: Thetrim() method removes leading and trailing whitespace from a string, returning a new string with the whitespace removed.

1
2
3
4

   const trimmedStr = str.trim();
   console.log(trimmedStr);  // Output: "Hello,   World!"
   

3. Use thereplace() method with a regular expression: Thereplace() method allows you to replace specific patterns within a string. You can use a regular expression to match whitespace characters and replace them with an empty string.

1
2
3
4
5

   const regex = /\s/g;  // Match all whitespace characters globally
   const removedWhitespaceStr = str.replace(regex, "");
   console.log(removedWhitespaceStr);  // Output: "Hello,World!"
   

4. Use thesplit() andjoin() methods: By splitting the string into an array based on whitespace characters and then joining the array elements, you can remove whitespace from the string.

1
2
3
4
5

   const splitStr = str.split(" ");     // Split the string by whitespace
   const removedWhitespaceStr = splitStr.join("");  // Join the array elements without whitespace
   console.log(removedWhitespaceStr);  // Output: "Hello,World!"
   

5. Use regular expressions with thereplace() method to remove all types of whitespace, including spaces, tabs, and line breaks:

1
2
3
4
5

   const regex = /\s/g;
   const removedWhitespaceStr = str.replace(regex, "");
   console.log(removedWhitespaceStr);  // Output: "Hello,World!"
   

Choose the method that best fits your requirements and the specific context in which you need to remove whitespace from a string. Thetrim() method is recommended for most cases as it removes leading and trailing whitespace. The other methods provide alternative approaches if you need to remove whitespace from specific positions within the string or in a more customized way.