2015-05-27 43 views
0

是否有一種簡單的方法將HTML代碼(以某種方式構建)轉換爲單個字符串用在一個Javascript變量中)。 html代碼中的新行和標籤需要轉換爲\ n和\ t,以便格式可以保持完整。如何將HTML代碼轉換爲用 n替換換行符的字符串並帶有 t的選項卡

例如HTML:

<html> 
    <head> 
     <title>Hello World</title> 
    </head> 
    <body> 
     <h1>Title</h1> 
      <h2>Subtitle</h2> 
       <p>Some text goes here</p> 
    </body> 
</html> 

我手動轉換這本:

<html>\n\n\t<head>\n\t\t <title>Hello World</title>\n \t</head>\n\n \t<body>\n \t\t<h1>Title</h1>\n \t\t\t<h2>Subtitle</h2>\n \t\t\t\t<p>Some text goes here</p>\n \t</body>\n\n </html>\n 

有一種簡單的方法來自動做到這一點?因爲我需要將更大的HTML塊轉換爲這種格式。謝謝。

+1

什麼後臺語言你有沒有在您的處置? – MyStream

+0

我希望有一個轉換器可以讓我粘貼HTML代碼並將其轉換爲該類型的字符串。如果沒有,我會確保我獲得正確的後端語言,因爲這種轉換必須以任何方式發生。 – jibly

+0

可能有兩個問題的重複[this](http://stackoverflow.com/questions/13532761/javascript-find-and-replace-line-breaks)和[this](http://stackoverflow.com/questions/4562756/replacement-tab-characters-in-javascript) –

回答

1
function format(data) { 
     var returnStr = ""; 
     var lines = data.split("\n"); 
     var block = []; 
     for (var i = 0; i < lines.length; i++) { 
      block = lines[i].split('\t'); 
      for (var j = 0; j < block.length; j++) { 
       returnStr += block[j]; 
       if (block.length>1) { 
        returnStr += "\\t"; 
       } 
      }; 
      returnStr += "\\n"; 
     }; 
     return returnStr; 
    } 
+0

tnx這是一個很好的開始! – jibly

0

如果你這樣做,以顯示新的行和返回馬車html,那麼你不需要明確做到這一點。你可以通過設置白色空間屬性預行值來在css中完成。

<span style="white-space: pre-line">CommentText</span> 
+0

謝謝,但我不能使用這種方法,因爲代碼被JavaScript通過代碼編輯器推入。 – jibly

+1

你試過用這個嗎? http://www.web2generators.com/html-based-tools/online-html-entities-encoder-and-decoder –

+0

它似乎沒有轉換格式。新的線條和標籤? – jibly

相關問題