javascript - 使用 JavaScript 突出显示和格式化代码片段

标签 javascript formatting syntax-highlighting highlight prettify

我正在寻找一种方法来突出显示并格式化作为实时风格指南字符串传递的代码片段。我正在玩 highlighjs 和 prettify。它们确实很有帮助并且易于突出显示,但我似乎无法找出格式化方法或它们是否真的可以做到这一点。

通过格式化,我指的是制表符和换行符,以使代码清晰易读。我需要将代码作为字符串传递,以自动输出我用于样式指南的灰尘模板。

也就是说,我想通过:

"<table><tr><td class="title">Name</td><td class="title">Category</td><td class="title">Results</td></tr></table>"

并得到类似的东西:

<table>
        <tr>
            <td class="title">Name</td>
            <td class="title">Category</td>
            <td class="title">Results</td>
        </tr>
</table>

关于如何实现这一目标有什么想法吗? 谢谢!

最佳答案

您可以将其作为 HTML 解析为 DOM,然后遍历每个元素,将其写出来并在每次迭代时缩进。

这段代码可以完成这项工作。请随意使用它并一定要改进它。它的版本是0.0.0.1。

var htmlString = '<table><tr><td class="title">Name</td><td class="title">Category</td><td class="title">Results</td></tr></table>';

//create a containing element to parse the DOM.
var documentDOM = document.createElement("div");
//append the html to the DOM element.
documentDOM.insertAdjacentHTML('afterbegin', htmlString);

//create a special HTML element, this shows html as normal text.
var documentDOMConsole = document.createElement("xmp");
documentDOMConsole.style.display = "block";

//append the code display block.
document.body.appendChild(documentDOMConsole);

function indentor(multiplier)
{
    //indentor handles the indenting. The multiplier adds \t (tab) to the string per multiplication.
    var indentor = "";
    for (var i = 0; i < multiplier; ++i)
    {
        indentor += "\t";
    }
    return indentor;
}

function recursiveWalker(element, indent)
{
    //recursiveWalker walks through the called DOM recursively.
    var elementLength = element.children.length; //get the length of the children in the parent element.

    //iterate over all children.
    for (var i = 0; i < elementLength; ++i)
    {
        var indenting = indentor(indent); //set indenting for this iteration. Starts with 1.
        var elements = element.children[i].outerHTML.match(/<[^>]*>/g); //retrieve the various tags in the outerHTML.
        var elementTag = elements[0]; //this will be opening tag of this element including all attributes.
        var elementEndTag = elements[elements.length-1]; //get the last tag.

        //write the opening tag with proper indenting to the console. end with new line \n
        documentDOMConsole.innerHTML += indenting + elementTag + "\n"; 

        //get the innerText of the top element, not the childs using the function getElementText
        var elementText = getElementText(element.children[i]);

        //if the texts length is greater than 0 put the text on the page, else skip.
        if (elementText.length > 0)
        {
            //indent the text one more tab, end with new line.
            documentDOMConsole.innerHTML += (indenting + indentor(1) ) + elementText+ "\n";
        }

        if (element.children[i].children.length > 0)
        {
            //when the element has children call function recursiveWalker.
            recursiveWalker(element.children[i], (indent+1));
        }

        //if the start tag matches the end tag, write the end tag to the console.
        if ("<"+element.children[i].nodeName.toLowerCase()+">" == elementEndTag.replace(/\//, ""))
        {
            documentDOMConsole.innerHTML += indenting + elementEndTag + "\n";
        }
    }
}

function getElementText(el)
{
        child = el.firstChild,
        texts = [];

    while (child) {
        if (child.nodeType == 3) {
            texts.push(child.data);
        }
        child = child.nextSibling;
    }

    return texts.join("");
}

    recursiveWalker(documentDOM, 1);

http://jsfiddle.net/f2L82m8h/

关于javascript - 使用 JavaScript 突出显示和格式化代码片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27748807/

相关文章:

javascript - 与react-router-dom 4 react - 无法读取未定义的属性 'params'

javascript - 如何使用 (location.hash) 和 (.trigger) 进行导航?

excel - (Excel) 基于相邻单元格值的条件格式

excel - 根据 .Value 更改 .NumberFormat

syntax-highlighting - 如何在Xcode 4中为文件类型分配语法颜色?

javascript - Chrome不支持通过javascript添加searchEngine 'window.external.AddSearchProvider(url)'

javascript - toLocaleString() 方法的奇怪行为

formatting - 在Tableau中,如何修改百分比标签的小数位数?

syntax-highlighting - Sublime Text 3 中的自定义语法高亮

visual-studio-2019 - 在 visual studio 2019 中更改 Javascript 的语法突出显示