JavaScriptStrings

String.prototype.trimStart()

Removes whitespace only from the start of a string. The end of the text stays unchanged.

Returns
A new string without whitespace at the start.
Changes the original
No
On this page

Example

#
JavaScript
const command = '   /help   '

console.log(`[${command.trimStart()}]`)
console.log(`[${command.trim()}]`)
Console
[/help ]
[/help]

Definition and usage

#

The trimStart() method returns a new string without spaces, tabs, newline characters, and other whitespace at the start. Spacing at the end and in the middle of the text is left untouched, and the original string is not changed.

It comes in handy when only the left side of the text matters: when reading a command typed into a chat with a stray space at the start, when stripping indentation from a line of code, or when measuring how deeply indented a given line is.

In older code you will come across the name trimLeft(). It is the same function under its old name, kept for compatibility. Use trimStart() in new code, since "start" is the right term even for languages written right to left, where the text begins on the right side.

Syntax

#
Syntax
string.trimStart()

More examples

#
Indentation depth of a line
JavaScript
const lines = ['function start() {', '  const level = 1', '    return level', '}']

for (const line of lines) {
  const indent = line.length - line.trimStart().length
  console.log(indent, line.trimStart())
}
Console
0 function start() {
2 const level = 1
4 return level
0 }
Newlines and tabs
JavaScript
const input = '\n\t  Answer: 42'

console.log(input.trimStart())
console.log(input.length, input.trimStart().length)
Console
Answer: 42
14 10
trimLeft() is the old name
JavaScript
console.log(String.prototype.trimLeft === String.prototype.trimStart)
console.log('  code'.trimLeft())
Console
true
code

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • trim() is usually the better choice for cleaning up form data. Reach for trimStart() when trailing spaces matter, or when you are deliberately keeping them.
  • The difference line.length - line.trimStart().length is the number of indentation characters. It comes in handy when analyzing code, bulleted lists, and configuration files.

Related entries

#

Spotted a mistake or missing an example? Write to us.