Last active
February 16, 2023 22:10
-
-
Save chriscauley/7b2c1227aae330d3f0dc5735a697c008 to your computer and use it in GitHub Desktop.
Nuke white space in <pre><code> tags
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Removes the minimum leading whitespace for each line in a pre > code tag. | |
Also optionally escapes html if you include the "nuke-html" class | |
When writing HTML snippets for slides or blogs, it's a pain to have to do this: | |
</div> <!-- original indentation level --> | |
<pre><code class="html"><ul class="demo"> | |
<li>No order here</li> | |
<li>Or here</li> | |
<li>Or here</li> | |
<li>Or here</li> | |
</ul></pre></code> | |
What you really want is this: | |
</div> | |
<pre><code class="html nuke-html"> | |
<ul class="demo"> | |
<li>No order here</li> | |
<li>Or here</li> | |
<li>Or here</li> | |
<li>Or here</li> | |
</ul> | |
</code></pre> | |
*/ | |
document.querySelectorAll("pre code").forEach(function(element,n) { | |
if (element.classList.contains("nuke-html")) { | |
var text = element.innerHTML; | |
} else { | |
var text = element.innerText; | |
} | |
text = text.replace(/^\n/,'').trimRight();// goodbye starting whitespace | |
var to_kill = Infinity; | |
var lines = text.split("\n"); | |
for (var i=0;i<lines.length;i++) { | |
if (!lines[i].trim()) { continue; } | |
to_kill = Math.min(lines[i].search(/\S/),to_kill); | |
} | |
out = []; | |
for (var i=0;i<lines.length;i++) { | |
out.push(lines[i].replace(new RegExp("^ {"+to_kill+"}","g"),"")); | |
} | |
element.innerText = out.join("\n"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Working very well. Thanks!