DEV Community

Mastering JS
Mastering JS

Posted on

7 2

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

Neon image

Set up a Neon project in seconds and connect from a Next.js application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

Top comments (0)

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay