javascript - HTML字串排版
迷茫
迷茫 2017-05-24 11:36:25
0
4
694

我現在有HTML程式碼的字串,想要對字串進行排版,有沒有什麼可用的方法?

需要一款js插件,或是方法,能在專案裡面轉換用的。

例如原始字串是:

This is a p

This is another p

新增空格和換行,變成新的字串:

This is a p

This is another p

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回覆 (4)
世界只因有你

第一種方案想用正規做答沒成功,沒有成功。
整理了下思路,已經完美解決(自認為完美)。

function codeFormat(code, indent, tmpIndent){ var indent = indent || ' '; var tmpIndent = tmpIndent || '\n'; var preg = /<(\S*)([^>]*)>([\s\S]*?)<\/>/ig; return code.replace(preg, function(
/* 感觉没什么难度,一个循环 遇见 >后跟<,换行 遇见 < 缩进 遇见 " && keyNext == "<" ){ result += "\n"; } } return result; } codeFormat("

This is a p

This is another p

"); /*

This is a p

This is another p

*/ codeFormat('

This is a p

This is another p

', ' '); /*

This is a p

This is another p

*/
, , , ){ return tmpIndent + '<' + + + '>' + codeFormat(, indent, tmpIndent + indent) + ( .trim().substr(0,1) == '<' ? tmpIndent : '') + ''; }); } codeFormat("

This is a p

This is anothers p

This is a p

This is another p

"); /*

This is a p

This is anothers p

This is a p

This is another p

*/ codeFormat('

This is a p

This is another p

', '----'); /* ---- -------- ---- ---- --------

------------

This is a p

------------

This is another p

--------

---- */

以下是循環的舊答案:

rrreee
    刘奇

    為什麼我這個問題一直被踩?還是一個不錯的問題的嘛。 。 。 。
    @mqycn , @zhenguoli

    這是朋友@candy寫的一個方案:

    import _ from 'lodash'; const splitOnTags = str => str.split(/(<\/?[^>]+>)/g).filter(line=>line.trim()!=""); const isTag = str => /<[^>!]+>/.test(str); const isClosingTag = str => /<\/[^>]+>/.test(str); const isSelfClosingTag = str => /<[^>]+\/>/.test(str); const isOpeningTag = str => isTag(str) && !isClosingTag(str) && !isSelfClosingTag(str); export default (str, indent) => { let depth = 0; indent = indent || ' '; return splitOnTags(str).map(item=>{ if(isClosingTag(item)) { depth--; } const line = _.repeat(indent, depth) + item; if(isOpeningTag(item)) { depth++; } return line; }).join('\n'); }
      黄舟

      http://tool.oschina.net/codef... 線上的。其他的編輯器裡面有beautify

        伊谢尔伦
        1. 對開發工具而言,你可以嘗試 VSCode 編輯器。

        https://code.visualstudio.com/

        安裝完成後,按 shift-ctrl-x 開啟插件列表,搜尋 Beautify 並安裝,即可實現 HTML 程式碼美化。
        對應設定參考這裡:

        https://marketplace.visualstu...

        1. 在程式碼中進行格式轉換可以使用 HTML String Parser,例如

        https://www.npmjs.com/package...

        或使用 cheerio 解析 DOM 文字後重新輸出亦可。

        3.(重新製作一個 HTML Parser 並不困難,參考我的專欄
        http://ewind.us/2016/toy-html...

          最新下載
          更多>
          網站特效
          網站源碼
          網站素材
          前端模板
          關於我們 免責聲明 Sitemap
          PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!