How to Left Trim a String in JavaScript

Jun 29, 2021

If you want to remove leading whitespace from a JavaScript string, the trimStart() function is what you're looking for. Equivalently, you can call trimLeft(), which is an alias for trimStart()

let example = '        Hello World';
example.trimStart(); // 'Hello World'
example.trimLeft(); // 'Hello World'

The trimStart() function is a relatively recent addition to JavaScript, so you need a polyfill if you want to use trimStart() in Internet Explorer or Node.js < 10.0.0. An alternative is to use the string replace() function with a regular expression.

// \s is a metacharacter representing any whitespace character
// See
example.replace(/^\s+/, ''); // 'Hello World'

Trimming Other Characters

You can also use replace() to remove any other set of characters from the beginning of the string. For example, suppose you want to remove any leading 'Na ' strings. You can use the regular expression /^(Na )+/. The ^ means at the beginning of the string, (Na) means the group Na, and + means one or more.

let example = 'Na Na Na Na Na Na Na Na Na Na Na Na Na Na Na Na BATMAN!';
example.replace(/^(Na )+/, ''); // 'BATMAN!'

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials