How to Remove Spaces From the Start of a JavaScript String?

Trim only space characters from the start of a string in JavaScript

To only remove space character(s) from the start of a string in JavaScript (which is different than removing whitespace characters), you can use a simple regular expression pattern like so:

/^ */

Where the regular expression pattern does the following:

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

For example:

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

console.log(newStr); // '\r\n\t\v\ffoo, bar, baz.  '

You can use the String.prototype.indexOf() method to verify that the first character in the new string is after "foo," (and none at the start of the string anymore):

newStr.indexOf(' '); // 9

Also, you can use the String.prototype.includes() (or String.prototype.indexOf()) method to verify that the new string has all the other whitespace characters preserved:

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

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