37

I currently have the following html within a pre-code block:

                <pre class="prettyprint"><code>
                    &lt;html&gt;
                    &lt;body&gt;

                    &lt;form name=&quot;input&quot; action=&quot;html_form_action.asp&quot; method=&quot;get&quot;&gt;
                    &lt;input type=&quot;radio&quot; name=&quot;sex&quot; value=&quot;male&quot;&gt;Male&lt;br&gt;
                    &lt;input type=&quot;radio&quot; name=&quot;sex&quot; value=&quot;female&quot;&gt;Female&lt;br&gt;
                    &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
                    &lt;/form&gt; 

                    &lt;p&gt;If you click the &quot;Submit&quot; button, the form-data will be sent to a page called &quot;html_form_action.asp&quot;.&lt;/p&gt;

                    &lt;/body&gt;
                    &lt;/html&gt;
                </code></pre>

It is indented within the html source for better structure within the document. How can I remove the leading whitespace? Through the use of javascript or is there a more simple method.

0

5 Answers 5

63

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-space property 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;
}
3
  • 9
    It removes non-leading repeated whitespace characters as well, which might not be desirable: jsfiddle.net/0zLv0nod
    – Corey
    Commented May 26, 2017 at 13:53
  • I want to remove whitespace on just the first line of a pretty printed json string and this solution removes indent from every line of the string. :-(
    – djangofan
    Commented Nov 14, 2020 at 2:48
  • @djangofan Put the indent for each line within the child tag. Commented May 30, 2022 at 10:26
10

I really like Homam's idea, but I had to change it to deal with this:

<pre><code><!-- There's nothing on this line, so the script thinks the indentation is zero -->
    foo = bar
</code></pre>

To fix it, I just take out the first line if it's empty:

[].forEach.call(document.querySelectorAll('code'), function($code) {
    var lines = $code.textContent.split('\n');

    if (lines[0] === '')
    {
        lines.shift()
    }

    var matches;
    var indentation = (matches = /^[\s\t]+/.exec(lines[0])) !== null ? matches[0] : null;
    if (!!indentation) {
        lines = lines.map(function(line) {
            line = line.replace(indentation, '')
            return line.replace(/\t/g, '    ')
        });

        $code.textContent = lines.join('\n').trim();
    }
});

(I'm also processing <code> tags instead of <pre> tags.)

3
  • 1
    Thanks, just what I needed, a nice modification to @homam's answer
    – ESR
    Commented Dec 15, 2016 at 14:51
  • Your answer can end at first code block, that snippet open my eyes...
    – gfdevelop
    Commented Sep 18, 2020 at 23:24
  • I moved $code.textContent = lines.join('\n').trim(); outside of the if statement to trim out a blank line even if the first line after that does not have indentation. Commented Jun 28, 2023 at 0:34
9

You may want to just change how it is output, but it is fairly simple to do with JavaScript

var p = document.querySelector(".prettyprint");
p.textContent = p.textContent.replace(/^\s+/mg, "");

http://jsfiddle.net/a4gfZ/

4
  • Thank you it worked exactly the way i wanted it! Just a general question is it more preferable for viewers to have the code wrap or for it just flow and scroll through?
    – Deep
    Commented Jun 23, 2013 at 3:47
  • @Deep I'd personally prefer it to wrap Commented Jun 23, 2013 at 4:09
  • 8
    Solves the particular example, but if the code itself is indented it would lose that indent. Commented Jun 11, 2014 at 0:54
  • 3
    Because of @CiroSantilli烏坎事件2016六四事件法轮功's comment, this answer isn't really a solution to the problem. It's just a monkeypatch for this particular manifestation of the problem.
    – ESR
    Commented Dec 15, 2016 at 14:36
8

Extending the above solution, this snippet assumes the indentation of the the first line inside <pre> is 0 and it realigns all the lines based on the first line:

[].forEach.call(document.querySelectorAll('pre'), function($pre) {
  var lines = $pre.textContent.split('\n');
  var matches;
  var indentation = (matches = /^\s+/.exec(lines[0])) != null ? matches[0] : null;
  if (!!indentation) {
    lines = lines.map(function(line) {
      return line.replace(indentation, '');
    });
    return $pre.textContent = lines.join('\n').trim();
  }
});
3
  • For me, this answer is the first one to actually solve the problem.
    – ESR
    Commented Dec 15, 2016 at 14:38
  • This does, however, strip HTML content (for formatting etc.) from the <pre> tag, which isn't desirable Commented Apr 7, 2017 at 9:20
  • If you replace the instances of textContent with innerHTML, this does fix the issue. It will be slower to run though, if that's a concern. Commented Apr 7, 2017 at 9:29
0

When you use pre, you should format its content to be exactly as you want it to be rendered. That’s the very idea of pre (preformatted text). But if it’s just indentation, you could use CSS: margin-left with a suitable negative value.

1
  • Only this solution worked for me. white-space: pre-line css put every line starting from left most which I don't want for my rest of the lines.
    – Suraj Lama
    Commented Jan 7, 2020 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.