Join my Laravel for REST API's course on Udemy 👀

Remove leading whitespaces from a JavaScript string

June 9, 2022  ‐ 1 min read

In JavaScript you often deal with input given by users, think of form data for example. In such cases you may wish to trim leading whitespaces of the given inputs.

To specifically remove only the leading whitespaces, whitespaces at the start of the string, you can use the .trimStart() string method.

let input = '  monday';
input = input.trimStart()
console.log(input)
// => 'monday'

The .trimStart() keeps the original String object intact and returns a new String object with the leading spaces stripped off.

If you prefer to also remove the trailing whitespaces at the end of the string, you can just use the .trim() method instead. This takes care of both the spaces at the beginning and end of the string.