一種方法可以遍歷字符串中的每行文本,和組他們通過縮進程度分爲幾個部分:
var leadingSpaces = /^\s*/;
blockOfText = blockOfText.replace(/\t/g, ' '); // replace tabs with 4 spaces
var lines = blockOfText.split('\n');
var sections = [];
var currentIndentLevel = null;
var currentSection = null;
lines.forEach(function(line) {
var indentLevel = leadingSpaces.exec(line)[0].length;
if (indentLevel !== currentIndentLevel) {
currentIndentLevel = indentLevel;
currentSection = { indentLevel: currentIndentLevel, lines: [] };
sections.push(currentSection);
}
currentSection.lines.push(line);
});
然後,一旦你擁有了這些部分,你可以通過他們的循環:
sections.forEach(function(section) {
switch (section.indentLevel) {
case 4:
// format as code
break;
// etc.
default:
// format as markdown
break;
}
});
嘿非常感謝,我會嘗試這種方法.. – Bmax