Last active
July 17, 2019 01:41
-
-
Save shanerk/95b870cd5ba5e1fd9915be4b093a8485 to your computer and use it in GitHub Desktop.
Un(in)dents a block of text (removing unwanted whitespace at the beginning of a line, but preserving desired indentation)
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 undentBlock(block) { | |
let REGEX_INDEX = /^[ \t]*\**[ \t]+/g; | |
let indent = null; | |
block.split("\n").forEach(function (line) { | |
let match = line.match(REGEX_INDEX); | |
let cur = match !== null ? match[0].replace(/\*/g, "").length : null; | |
if (cur < indent || indent === null) indent = cur; | |
}); | |
let ret = ""; | |
block.split("\n").forEach(function (line) { | |
line = undent(line, indent); | |
ret += line; | |
}); | |
return ret; | |
} | |
function undent(str, remove) { | |
let ret = ""; | |
let count = 0; | |
for (var i = 0; i < str.length; i++) { | |
let c = str.charAt(i); | |
if ((c === " " || c === "*") && count <= remove) { | |
count++; | |
} else { | |
break; | |
} | |
} | |
ret = str.substr(count, str.length); | |
if (ret === "\n" || ret === " ") ret; | |
return ret + "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment