【问题标题】:text formatting according to indentation根据缩进的文本格式
【发布时间】:2014-04-06 21:37:45
【问题描述】:

您好,有人可以帮我了解 stackoverflow 问题的代码区域是如何工作的(技术上)。
我的意思是它在缩进文本时格式化文本的方式。

示例:没有缩进

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

谁能解释一下这背后的技术。我是编程新手,这很难实现吗?我们如何根据文本的缩进来实现这种格式。

【问题讨论】:

    标签: html wysiwyg word-processor openwysiwyg


    【解决方案1】:

    一种方法是遍历字符串中的每一行文本,并按缩进级别将它们分组:

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

    【讨论】:

      猜你喜欢
      • 2018-12-07
      • 2023-01-03
      • 1970-01-01
      • 2011-06-18
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多