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
How to write a Regular Expression in JavaScript to remove spaces?
To remove spaces from strings in JavaScript, regular expressions provide a powerful and flexible solution. The most common approach uses the /\s/g pattern with the replace() method.
Basic Syntax
string.replace(/\s/g, '')
Where:
-
\s- matches any whitespace character (spaces, tabs, newlines) -
g- global flag to replace all occurrences -
''- empty string replacement
Example: Removing All Spaces
<html>
<head>
<script>
var str = "Welcome to Tutorialspoint";
document.write("Original: " + str);
// Removing all spaces
var result = str.replace(/\s/g, '');
document.write("<br>After removing spaces: " + result);
</script>
</head>
<body>
</body>
</html>
Original: Welcome to Tutorialspoint After removing spaces: WelcometoTutorialspoint
Different Types of Space Removal
<html>
<head>
<script>
var text = " Welcome to Tutorialspoint ";
// Remove all whitespace
document.write("All spaces: " + text.replace(/\s/g, ''));
// Remove only regular spaces (not tabs/newlines)
document.write("<br>Only spaces: " + text.replace(/ /g, ''));
// Remove leading/trailing spaces only
document.write("<br>Trim spaces: " + text.replace(/^\s+|\s+$/g, ''));
// Replace multiple spaces with single space
document.write("<br>Single spaces: " + text.replace(/\s+/g, ' '));
</script>
</head>
<body>
</body>
</html>
All spaces: WelcometoTutorialspoint Only spaces: Welcome to Tutorialspoint Trim spaces: Welcome to Tutorialspoint Single spaces: Welcome to Tutorialspoint
Regular Expression Patterns
| Pattern | Description | Example |
|---|---|---|
/\s/g |
All whitespace characters | Removes spaces, tabs, newlines |
/ /g |
Only space characters | Keeps tabs and newlines |
/^\s+|\s+$/g |
Leading and trailing spaces | Equivalent to trim() |
/\s+/g |
Multiple consecutive spaces | Replaces with single space |
Modern Alternative Using trim()
<html>
<head>
<script>
var str = " Welcome to Tutorialspoint ";
// Using built-in trim() method
document.write("Original: '" + str + "'");
document.write("<br>Trimmed: '" + str.trim() + "'");
// Combining trim() with replace() for complete removal
document.write("<br>All spaces removed: '" + str.trim().replace(/\s/g, '') + "'");
</script>
</head>
<body>
</body>
</html>
Original: ' Welcome to Tutorialspoint ' Trimmed: 'Welcome to Tutorialspoint' All spaces removed: 'WelcometoTutorialspoint'
Conclusion
Regular expressions provide flexible space removal in JavaScript. Use /\s/g for all whitespace, / /g for spaces only, or combine with trim() for comprehensive string cleaning based on your specific requirements.
Advertisements
