trimStart()

ES2019+

Removes whitespace from the beginning of a string.

Syntax

string.trimStart()

Return Value

string

A new string with whitespace removed from the start

Examples

JavaScript
const str = '   Hello';
console.log(str.trimStart());
Output:
// 'Hello'

📌 When to Use

Use trimStart() when you need to preserve trailing whitespace but remove leading whitespace, such as when formatting code snippets, processing indented text, or handling text where trailing spaces are significant.

⚠️ Common Mistakes

Using trimStart() when trim() would be more appropriate - only use trimStart() when you specifically need to preserve trailing whitespace.

Not knowing the alias trimLeft() - both work identically, but trimStart() is the standard name in ES2019+.

Forgetting to check browser compatibility - trimStart() was added in ES2019 and may not work in older browsers without polyfills.

✅ Best Practices

Use trimStart() instead of regex like str.replace(/^\s+/, "") for cleaner and more efficient code.

Consider using trimStart() when processing heredocs or multiline template literals where indentation alignment matters.

For older browser support, use the alias trimLeft() or include a polyfill for trimStart().

⚡ Performance Notes

trimStart() is optimized to scan only from the beginning of the string, making it slightly more efficient than trim() when you only need to remove leading whitespace. However, the difference is negligible for most use cases.

🌍 Real World Example

Code Formatting and Indentation Handling

trimStart() is useful when processing code snippets or text blocks where you want to remove leading indentation while preserving trailing spaces that might be part of the content.

// Remove leading whitespace from each line in code block
function dedentCode(code) {
  const lines = code.split('\n');
  // Find minimum indentation (ignoring empty lines)
  const minIndent = lines
    .filter(line => line.trim().length > 0)
    .reduce((min, line) => {
      const indent = line.length - line.trimStart().length;
      return Math.min(min, indent);
    }, Infinity);

  // Remove the minimum indentation from all lines
  return lines
    .map(line => line.slice(minIndent))
    .join('\n');
}

const indentedCode = `
    function hello() {
        console.log('Hello');
    }
`;
console.log(dedentCode(indentedCode));

// Process user input where leading spaces were accidental
function normalizeListItem(item) {
  // Remove accidental leading spaces but keep trailing spaces
  // (might be intentional formatting)
  return item.trimStart();
}

const items = ['  Apple', '   Banana', 'Cherry  '];
console.log(items.map(normalizeListItem));
// Output: ['Apple', 'Banana', 'Cherry  ']

Related Methods