【问题标题】:Convert InnerHTML to human readable code将 InnerHTML 转换为人类可读的代码
【发布时间】:2015-05-05 13:02:41
【问题描述】:

我正在编写一个代码以从div 获取 html 代码并将其放入文本框中进行编辑。 如果我只是获取代码并直接打印它,我会得到:

<h1>hi</h1><p>Sloppy long one line</p><p>and so on</p>

这很难读,所以我想要这样:

<h1>
hi
</h1>
<p>
Sloppy long one line
</p>
<p>
and so on
</p>

我有这个:

function add_code()
{
    var html= document.getElementById("body_visual_editor").innerHTML //Gets the code
    html= html.replace(/draggable="true"/g, ''); //Removes the draggable attributes that are added to the elements when returning the code to the div 
    html= html.replace(/id="autoid[0-9]+"/g, ''); ////Removes the auto generated ID's that are added to the elements when returning the code to the div
    html= html.replace(/</g, '\n<'); //Adds a line break before tags
    html= html.replace(/\n\n/g, '\n'); //Fixes glitch caused by previous line
    html= html.replace(/>(?!\n)/g, '>\n'); //Adds line break after tag
    document.getElementById("body_code_box").value= html.trim(); //Adds the code to the textarea for editing.
}

它的问题:

当我删除可拖动属性时,它会在标签末尾留下 2 个空格。

当我在标签之前添加换行符时,即使已经有一个换行符,它也会添加额外的换行符,所以我需要html= html.replace(/\n\n/g, '\n') 来删除它。

该修复在代码开头留下了一个额外的换行符,所以我需要修剪来删除它。

它有效,但看起来很草率。有没有更好的方法来写这个更精简和有效?请不要使用 JQuery。

【问题讨论】:

  • 我不同意第一个例子很难阅读。
  • @canon: 大概“Sloppy long one line”比示例中的长很多很多..
  • @mellamokb 我认为以这种方式添加换行符(没有制表符或空格用于嵌套)甚至更糟。还不如进行完整的格式化实现,即:prettify.
  • @connon:缩进代码并正确格式化会很好。但由于这一切都是单独使用 JavaScript 完成的,所以我做的格式越多,代码就越复杂,所以现在换行符至少使它具有足够的可读性,可以理解和编辑。

标签: javascript html


【解决方案1】:

好的。我想我明白你想要什么。

var text = document.getElementById("yourDiv").innerHTML;
var find = '<';
var re = new RegExp(find, 'g');
text = text.replace(re, '\n<');
find = '>';
var re = new RegExp(find, 'g');
text = text.replace(re, '>\n');

这是JSFiddle

【讨论】:

  • 这不显示@Zaper127 要求的html标签
  • 我没有得到他想要的。带有或不带有标签的文本?使用标签:使用innerHTML。没有:innerText.
  • 嗯,对不起,但作为一个非英语母语人士,我对这些术语有一些问题,所以我不知道它们是什么意思,而且由于他使用的方式他们,我不认为我会找到一个简单的方法来翻译它们。
  • 我主要关心的是找到一个解决方案,即我不必为了清理代码而删除连续的换行符。有没有我可以使用的正则表达式,就像我为 > 设置的一样?此外,删除属性留下的额外空格使代码看起来有点混乱。
【解决方案2】:

奇怪的是,这个问题从来没有得到正确的回答。所需要做的就是用它们的相对实体名称替换 HTML 字符。

像这样(运行 sn-p 以查看它的实际效果):

let text = document.getElementById('raw').innerHTML,
find = '<',
re = new RegExp(find, 'g');
text = text.replace(re, '&lt;');

find = '>';
re = new RegExp(find, 'g');
text = text.replace(re, '&gt;');

document.getElementById('CodeOut').innerHTML = text;
<section id="raw">
<h1>hi</h1><p>Sloppy long one line</p><p>and so on</p>
</section>
<section id="Code" style="background-color:grey;color:#fff;padding:10px;">
<pre><code id="CodeOut"></code></pre>
</section>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多