Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Remove all whitespaces from string - JavaScript
We are required to write a JavaScript function that takes in a string and returns a new string with all the characters of the original string but with whitespaces removed.
Method 1: Using a For Loop
This approach iterates through each character and builds a new string excluding spaces:
const str = "This is an example string from which all whitespaces will be removed";
const removeWhitespaces = str => {
let newStr = '';
for(let i = 0; i < str.length; i++){
if(str[i] !== " "){
newStr += str[i];
}
}
return newStr;
};
console.log(removeWhitespaces(str));
Thisisanexamplestringfromwhichallwhitespaceswillberemoved
Method 2: Using replace() with Regular Expression
The replace() method with regex /\s/g removes all whitespace characters globally:
const str = "This is an example string from which all whitespaces will be removed"; const removeWhitespaces = str => str.replace(/\s/g, ''); console.log(removeWhitespaces(str));
Thisisanexamplestringfromwhichallwhitespaceswillberemoved
Method 3: Using split() and join()
Split the string by spaces and join the parts back together:
const str = "This is an example string from which all whitespaces will be removed";
const removeWhitespaces = str => str.split(' ').join('');
console.log(removeWhitespaces(str));
Thisisanexamplestringfromwhichallwhitespaceswillberemoved
Comparison
| Method | Performance | Readability | Handles All Whitespace Types |
|---|---|---|---|
| For Loop | Fast | Verbose | Only spaces |
| replace() with regex | Fast | Concise | Yes (tabs, newlines, etc.) |
| split() and join() | Moderate | Very readable | Only spaces |
Handling Different Whitespace Types
The regex method handles all whitespace characters including tabs and newlines:
const str = "Text with\ttabs\nand\r\nnewlines and spaces";
console.log("Original:", str);
console.log("Cleaned:", str.replace(/\s/g, ''));
Original: Text with tabs and newlines and spaces Cleaned: Textwithtabsandnewlinesandspaces
Conclusion
Use replace(/\s/g, '') for the most comprehensive whitespace removal. For simple space removal, split(' ').join('') offers excellent readability.
Advertisements
