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.