DEV Community

Mastering JS
Mastering JS

Posted on

How to Left Trim a String in JavaScript

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'
Enter fullscreen mode Exit fullscreen mode

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 https://www.w3schools.com/jsref/jsref_regexp_whitespace.asp
example.replace(/^\s+/, ''); // 'Hello World'
Enter fullscreen mode Exit fullscreen mode

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!'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)