Remove any leading spaces from the start of a string?

Answered
moon_man41 asked this question 11 months ago
moon_man41 on Mar 13, 2022 · Edited

In my JavaScript application, I am often dealing with strings that are either going to be saved to my database or retrieved from the database.

When dealing with those strings, I need to remove any unnecessary leading spaces from them.

For instance, this string:

"   My string example."

Should be converted to a new string that doesn't have the leading spaces:

"My string example.

Is there a simple way to do that in JavaScript?

3 suggested answers
nick on Apr 9, 2022

You can use the trimStart() JavaScript method:

string.trimStart()

That will remove all leading spaces from your string.

0 replies
coderguy on Apr 9, 2022

You have some easy options that are built into JavaScript:

  • trim(): removes leading and trailing spaces from your string.
  • trimStart(): removes leading spaces from your string.
  • trimEnd(): removes trailing spaces from your string.
0 replies
yaboy01 on Apr 9, 2022

This regular expression will remove any leading white space from your string:

string.replace(/^\s+/g, "");
0 replies
Answered