Trim whitespace

3 snippets across 3 stacks - JavaScript, Regular Expressions, SQL

JSJavaScript

Trimming Whitespace

JS · Strings
Syntax
str.trim()
str.trimStart()
str.trimEnd()
Example
const input = "  [email protected]  ";
console.log(input.trim());       // "[email protected]"
console.log(input.trimStart());  // "[email protected]  "
console.log(input.trimEnd());    // "  [email protected]"

Note Essential for cleaning user input. Only removes whitespace characters (spaces, tabs, newlines), not other invisible characters.

RXRegular Expressions

Whitespace Trimming

RX · Common Patterns
Syntax
/^\s+|\s+$/g
Example
JS:  '  hello world  '.replace(/^\s+|\s+$/g, '')
Py:  re.sub(r'^\s+|\s+$', '', '  hello world  ')
Output
"hello world"

Note Equivalent to str.trim() in JS and str.strip() in Python. The regex version is useful when you also want to normalize internal whitespace: replace /\s+/g with ' ' after trimming.

SQLSQL

TRIM / LTRIM / RTRIM

SQL · String Functions
Syntax
TRIM([LEADING|TRAILING|BOTH] [chars] FROM string)
LTRIM(string)
RTRIM(string)
Example
SELECT
  TRIM('  Alice  ') AS trimmed,
  TRIM(LEADING '0' FROM '000425') AS no_leading_zeros,
  LTRIM('  hello') AS left_trimmed,
  RTRIM('hello  ') AS right_trimmed;
Output
-- trimmed | no_leading_zeros | left_trimmed | right_trimmed
-- Alice   | 425              | hello        | hello

Note TRIM with no arguments removes whitespace from both sides. You can specify characters to trim. LTRIM and RTRIM are shorthand for leading/trailing trim. Clean user input with TRIM before storing.

Frequently asked questions

How do you trim whitespace?
This task is covered in 3 stacks on this page: JavaScript, Regular Expressions, SQL. The "Trimming Whitespace" snippet in JavaScript uses `str.trim()`.
Which code does the JavaScript example use?
The "Trimming Whitespace" snippet uses `str.trim()`, from the Strings section of the JavaScript cheat sheet.
Which stacks cover "trim whitespace" on this page?
JavaScript, Regular Expressions, SQL. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Trimming Whitespace": Essential for cleaning user input. Only removes whitespace characters (spaces, tabs, newlines), not other invisible characters.