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 extra spaces in string JavaScript?
To remove extra spaces from strings in JavaScript, you can use several methods depending on your needs. Here are the most common approaches.
Remove All Spaces
To remove all spaces from a string, use the replace() method with a regular expression:
var sentence = "My name is John Smith ";
console.log("Original string:");
console.log(sentence);
var noSpaces = sentence.replace(/\s+/g, '');
console.log("After removing all spaces:");
console.log(noSpaces);
Original string: My name is John Smith After removing all spaces: MynameisJohnSmith
Remove Leading and Trailing Spaces
Use trim() to remove spaces only from the beginning and end:
var sentence = " My name is John Smith ";
console.log("Original string:");
console.log('"' + sentence + '"');
var trimmed = sentence.trim();
console.log("After trim():");
console.log('"' + trimmed + '"');
Original string: " My name is John Smith " After trim(): "My name is John Smith"
Remove Extra Spaces Between Words
To collapse multiple spaces into single spaces while keeping words separated:
var sentence = "My name is John Smith";
console.log("Original string:");
console.log(sentence);
var normalized = sentence.replace(/\s+/g, ' ').trim();
console.log("After normalizing spaces:");
console.log(normalized);
Original string: My name is John Smith After normalizing spaces: My name is John Smith
Method Comparison
| Method | Purpose | Example Result |
|---|---|---|
replace(/\s+/g, '') |
Remove all spaces | "MynameisJohn" |
trim() |
Remove leading/trailing only | "My name is John" |
replace(/\s+/g, ' ').trim() |
Normalize to single spaces | "My name is John" |
Conclusion
Choose the method based on your needs: replace(/\s+/g, '') for complete removal, trim() for edge cleanup, or replace(/\s+/g, ' ').trim() for normalizing multiple spaces to single spaces.
Advertisements
