The question asks if there’s a JavaScript solution or a simpler method for removing leading whitespace. There’s a simpler method:
CSS
pre, code {
white-space: pre-line;
}
DEMO
white-space
The
white-spaceproperty is used to describe how whitespace inside the
element is handled.pre-line
Sequences of whitespace are collapsed.
To preserve existing whitespace or indentation, each line can be wrapped in a child tag with white-space reset to pre at the line level:
HTML
<pre>
<code>
<i>fn main() {</i>
<i> println!("hello world!");</i>
<i>}</i>
</code>
</pre>
CSS
pre, code {
white-space: pre-line;
}
pre > code > i {
white-space: pre;
}