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

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
// ...

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.