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
Example
#const command = ' /help '
console.log(`[${command.trimStart()}]`)
console.log(`[${command.trim()}]`)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
#string.trimStart()More examples
#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())
}const input = '\n\t Answer: 42'
console.log(input.trimStart())
console.log(input.length, input.trimStart().length)console.log(String.prototype.trimLeft === String.prototype.trimStart)
console.log(' code'.trimLeft())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 fortrimStart()when trailing spaces matter, or when you are deliberately keeping them.- The difference
line.length - line.trimStart().lengthis the number of indentation characters. It comes in handy when analyzing code, bulleted lists, and configuration files.
Related entries
#- String.prototype.trim()Removes whitespace from both ends of a string: spaces, tabs, and newline characters.
- String.prototype.trimEnd()Removes whitespace only from the end of a string, including trailing newline characters.
- String.prototype.padStart()Pads a string on the left with the given text until it reaches the specified length. Perfect for leading zeros.
- String.prototype.startsWith()Checks whether a string starts with the given text. Returns true or false.
Spotted a mistake or missing an example? Write to us.