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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay