Created
May 17, 2011 08:37
-
-
Save micmath/976164 to your computer and use it in GitHub Desktop.
Trim leading whitespace from code examples
This file contains hidden or 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
function escapeHtml(str) { | |
return str.toString().replace(/</g, "<").replace(/>/g, ">").replace(/&(\s)/g, "&$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