2017-06-15 20 views
2

特定位置我有一個數據文件,如下所示,如何更新數據到一個文件中的js

Test.txt, 
    <template class="get" type="amp-mustache"> 
     <div class="divcenter"> 
/////Need to append data at this point///// 
     </div> 
    </template> 

我有一個像下面

[ 
    {'text':'<p>grapes</p>'}, 
    {'text':'<p>banana</p>'}, 
    {'text':'<p>orange</p>'}, 
    {'text':'<p>apple</p>'}, 
    {'text':'<p>gua</p>'} 
] 

數據追加數據後應該是,

<template class="get"> 
     <div class="divcenter"> 
     <p>grapes</p> 
     <p>banana</p> 
     <p>orange</p> 
     <p>apple</p> 
     <p>gua</p> 
     </div> 
    </template> 

我的代碼,

fs.readFile(Test.txt, function read(err, data) { 
    if (err) { 
      throw err; 
    } 
    var file_content = data.toString(); 
    var c = file_content.indexOf(' <div class="divcenter">'); 
}); 

但是,如何找到索引後追加?

+0

嘗試使用一些解析器,如https://github.com/tmpvar/jsdom,爲什麼你標記了angularjs :) – codtex

+0

嗨codtex,因爲這與js有關,一些專家喜歡可能來形成角js ... :) –

回答

0

這不是隻使用substr

var needle = '<div class="divcenter">'; 
var newString = file_content.substr(0, c + needle.length) 
    + '__NEW_STRING__' 
    + file_content.substr(needle.length - 1); 

編輯最優雅的方式:

更優雅的方式是遍歷字符串作爲DOM使用cheerio

0

你可以這樣做:

  • 找到要插入您的字符串
  • 片源字符串,並插入新的字符串

    fs.readFile(Test.txt, function read(err, data) { 
        if (err) { 
         throw err; 
        } 
        var file_content = data.toString(); 
        var str = "<p>grapes</p> 
          <p>banana</p> 
          <p>orange</p> 
          <p>apple</p> 
          <p>gua</p>"; 
        var idx = file_content.indexOf('<div class="divcenter">') + '<div class="divcenter">'.length; 
        var result = file_content.slice(0, idx) + str + file_content.slice(idx); 
    }); 
    
0

爲什麼不能索引在jQuery中做。

使用循環做這樣的:

var uiDiv = $(".divcenter"); 
for(var i=0; i<data.length; i++){ 
    uiDiv.append("<p>'"+data[i]+"'</p>"); 
} 

希望工程。

相關問題