How to Remove Whitespace Characters From the Start of a JavaScript String?

Trim whitespace characters from the start of a string in JavaScript

To remove whitespace characters from the start of a string (which is different than removing only space characters), you can use any of the following methods:

Using String.prototype.trimStart()

Introduced in ES10, you can use the String.prototype.trimStart() method to remove whitespace characters from the start of a string.

Please note that the String.prototype.trimStart() method returns a new string with stripped out whitespace characters from the left-most side of a given string. A new string is returned regardless of whether there is whitespace at the start of the string or not.

For example:

// ES10+
const str = '\r\n\t\v\f    foo, bar, baz. ';
const newStr = str.trimEnd();

console.log(newStr); // 'foo, bar, baz. '

Please be aware that for web compatibility reasons, the String.prototype.trimLeft() method remains as an alias to the String.prototype.trimStart() method. However, you should use String.prototype.trimStart() wherever possible.

Using a Regular Expression

If you're unable to support ES10, you may use a simple regular expression to remove any number of whitespace characters from the start of a string. For example:

const str = '\r\n\t\v\f    foo, bar, baz. ';
const newStr = str.replace(/^\s*/, '');

console.log(newStr); // 'foo, bar, baz. '

The regular expression pattern does the following:

  • ^ — Matches at only the start of the string;
  • \s* — Matches any number of whitespace characters.

How to Verify the Whitespace Characters are Removed?

To verify the new string has all the whitespace characters removed, you can use the String.prototype.includes() (or String.prototype.indexOf()) method like so:

// ES6+
newStr.includes('\r'); // false
newStr.includes('\n'); // false
// ...

Since the string has multiple instances of the space character, you can use the String.prototype.indexOf() method to verify that the first space character in the new string is after "foo," (and not at the start of the string anymore):

newStr.indexOf(' '); // 4

Hope you found this post useful. It was published . Please show your love and support by sharing this post.