2014-03-05 43 views
0

嗨,有人可以幫助我理解stackoverflow問題的代碼區域是如何工作的(技術上)。
我的意思是它將文本格式化爲縮進文本的方式。根據縮進的文本格式

例如:無壓痕

example: with indentation (text background color and font has changed) 

有人可以解釋我的技術這背後。我是編程新手,這是很難實現的東西。我們如何根據文本的縮進來實現這種格式。

回答

0

一種方法可以遍歷字符串中的每行文本,和組他們通過縮進程度分爲幾個部分:

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; 
    } 
}); 
+0

嘿非常感謝,我會嘗試這種方法.. – Bmax