Skip to content

Instantly share code, notes, and snippets.

@micmath
Created May 17, 2011 08:37
Show Gist options
  • Save micmath/976164 to your computer and use it in GitHub Desktop.
Save micmath/976164 to your computer and use it in GitHub Desktop.
Trim leading whitespace from code examples
function escapeHtml(str) {
return str.toString().replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/&(\s)/g, "&amp;$1");
}
function prepareCodeExample(str) {
str = str.toString();
//remove blank lines at the start and end of the example
var description = str.match(/^\s*.*\s*()/)
str = str.replace(/^(\s*[\r\n]+)+/, "").replace(/([\r\n]+\s+)+$/, "");
//read the space at the start for the 1st line of code
var startGap = str.match(/^\s*/)[0];
//remove that from all lines, hopefully normalising the tab indent
str = str.replace(new RegExp("^" + startGap, "mg"), "").replace(/\t/g, " ");
return escapeHtml(str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment