从pre/code标签中的缩进HTML源中删除前导空格

Dee*_*eep 18 html javascript css regex jquery

我目前在预代码块中有以下html:

                <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>
Run Code Online (Sandbox Code Playgroud)

它在html源代码中缩进,以便在文档中获得更好的结构.如何删除前导空格?通过使用javascript还是有一个更简单的方法.

Mic*_*l_B 35

问题是询问是否有JavaScript解决方案或更简单的方法来删除前导空格.有一个更简单的方法:

CSS

pre, code {
    white-space: pre-line;
}
Run Code Online (Sandbox Code Playgroud)

DEMO

空白

white-space属性用于描述如何处理元素内的空白.

前行

空白的序列被折叠.

  • 它也删除了非领先的重复空白字符,这可能是不可取的:http://jsfiddle.net/0zLv0nod/ (4认同)

vol*_*evo 6

我真的很喜欢Homam的想法,但我不得不改变它来处理这个问题:

<pre><code><!-- There's nothing on this line, so the script thinks the indentation is zero -->
    foo = bar
</code></pre>
Run Code Online (Sandbox Code Playgroud)

要解决这个问题,如果它是空的,我只需取出第一行:

[].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();
    }
});
Run Code Online (Sandbox Code Playgroud)

(我也在处理<code>标签而不是<pre>标签.)


Exp*_*lls 5

您可能只想更改其输出方式,但是使用JavaScript相当简单

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

http://jsfiddle.net/a4gfZ/

  • 解决了特定的示例,但是如果代码本身缩进,则将丢失该缩进。 (7认同)
  • 由于@CiroSantilli乌坎事件2016六四事件法轮功的评论,此答案实际上并不是解决问题的方法。这只是问题的这种特殊表现的一个小补丁。 (3认同)

hom*_*mam 5

扩展上述解决方案,此代码段假定内部第一行的缩进<pre>为 0,并根据第一行重新对齐所有行:

[].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();
  }
});
Run Code Online (Sandbox Code Playgroud)