🔍Regex Recipes

Trim Leading/Trailing Whitespace

Remove whitespace from start and end of lines with multiline variations.

Pattern

^\s+|\s+$

Explanation

Matches whitespace at the start (^\s+) or end (\s+$) of string. Use multiline flag for each line.

Examples

Leading spaces
Input
   text
Output
Replace with: text
Trailing spaces
Input
text   
Output
Replace with: text
Both sides
Input
  text  
Output
Replace with: text
Already trimmed
Input
text
Output
No change

Code Examples

JavaScript
// Single line trim
const text = '  hello world  ';
const trimmed = text.replace(/^\s+|\s+$/g, '');
// Or use built-in: text.trim()

// Trim each line in multiline text
const multiline = `
  line 1  
  line 2  
`;
const trimmedLines = multiline
  .replace(/^\s+|\s+$/gm, '');

Try it Now

💡 Tips

  • In JavaScript, use .trim() for simple cases
  • Add m flag for multiline trimming
  • Combine with duplicate space removal for full normalization
  • Consider trimStart() and trimEnd() for one-sided trimming

⚠️ Common Pitfalls

  • Use multiline flag (m) to trim each line separately
  • May want to preserve intentional indentation
  • Built-in trim() is usually better for simple cases
  • Does not normalize internal whitespace