removeExtraSpaces
Removes leading, trailing, and multiple consecutive spaces from a string.
1/**
2 * Removes leading, trailing, and multiple consecutive spaces from a string.
3 *
4 * @param str - The input string.
5 * @returns A cleaned string with single spaces between words.
6 */
7export function removeExtraSpaces(str: string): string {
8 return str.trim().replace(/\s+/g, ' ');
9}
Cleans Up Whitespace Efficiently
Combines
trim()
and a regular expression to remove leading/trailing whitespace and collapse multiple internal spaces into a single space.Improves Consistency in Text
Ensures uniform spacing, which is essential for comparing, storing, or displaying user input cleanly.
Simple and Lightweight
One-liner solution that is easy to understand and performant even on large strings.
Language-Agnostic & Safe
Handles spacing consistently across languages, including those with non-Latin characters.
Tests | Examples
1test('removeExtraSpaces - trims and reduces internal spaces', () => {
2 expect(removeExtraSpaces(' Hello world ')).toBe('Hello world');
3});
4
5test('removeExtraSpaces - handles tabs and newlines', () => {
6 expect(removeExtraSpaces('\tHello\n\nworld\t')).toBe('Hello world');
7});
8
9test('removeExtraSpaces - returns same string if no extra spaces', () => {
10 expect(removeExtraSpaces('Hello world')).toBe('Hello world');
11});
12
13test('removeExtraSpaces - empty string remains empty', () => {
14 expect(removeExtraSpaces('')).toBe('');
15});
16
17test('removeExtraSpaces - only whitespace', () => {
18 expect(removeExtraSpaces(' \n\t ')).toBe('');
19});
Common Use Cases
User Input Normalization
Clean form inputs like names, addresses, or messages before saving to a database.
Search Optimization
Standardize strings before performing text comparisons or full-text searches.
Display Formatting
Present clean text in the UI by removing excessive or accidental spacing.
Data Cleanup
Useful in ETL (Extract, Transform, Load) pipelines or preprocessing CSV/TSV content with inconsistent spacing.
Natural Language Processing (NLP)
Preprocess text before tokenization or analysis in NLP models.