To remove all leading spaces:
str = str.replace(/^ +/gm, '');
The regular expression is pretty simple - one or more spaces at the beginning. More interesting bits are the flags - /g (global) to replace all matches, not just the first ones, and /m (multi-line) so that the caret matches the beginning of each line, and not just the beginning of the line.
Working example: http://jsbin.com/oyeci4
source share