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
Remove the whitespaces from a string using replace() in JavaScript?
In JavaScript, the Use the regex For removing leading and trailing whitespaces, JavaScript's built-in The replace()
Basic Syntax
string.replace(regex, replacement)
Removing Leading and Trailing Whitespaces
/^\s+|\s+$/g to remove whitespaces from the beginning and end of a string:
function removeSpacesAtTheBeginningAndTheEnd(name) {
return name.toString().replace(/^\s+|\s+$/g, '');
}
var fullName = " John Smith ";
var valueAfterRemovingSpace = removeSpacesAtTheBeginningAndTheEnd(fullName);
console.log("Original: '" + fullName + "'");
console.log("Trimmed: '" + valueAfterRemovingSpace + "'");
Original: ' John Smith '
Trimmed: 'John Smith'
Different Types of Whitespace Removal
Remove All Whitespaces
var text = " Hello World ";
var noSpaces = text.replace(/\s/g, '');
console.log("'" + text + "' ? '" + noSpaces + "'");
' Hello World ' ? 'HelloWorld'
Remove Only Leading Whitespaces
var text = " Hello World ";
var noLeadingSpaces = text.replace(/^\s+/, '');
console.log("'" + text + "' ? '" + noLeadingSpaces + "'");
' Hello World ' ? 'Hello World '
Remove Only Trailing Whitespaces
var text = " Hello World ";
var noTrailingSpaces = text.replace(/\s+$/, '');
console.log("'" + text + "' ? '" + noTrailingSpaces + "'");
' Hello World ' ? ' Hello World'
Regex Pattern Explanation
Pattern
Description
Result
/^\s+|\s+$/gLeading OR trailing spaces
Trims both ends
/\s/gAll whitespace characters
Removes all spaces
/^\s+/Only leading spaces
Removes from start
/\s+$/Only trailing spaces
Removes from end
Alternative: Using trim()
trim() method is more concise:
var fullName = " John Smith ";
console.log("Using replace(): '" + fullName.replace(/^\s+|\s+$/g, '') + "'");
console.log("Using trim(): '" + fullName.trim() + "'");
Using replace(): 'John Smith'
Using trim(): 'John Smith'
Conclusion
replace() method with regex provides flexible whitespace removal options. For simple trimming, use the built-in trim() method, but use replace() when you need more specific whitespace control.
