加载文件并解析文档

时间:2018-11-29 12:51:45

标签: javascript html parsing web

我有一个代码,可以用HTML显示整个文档

    <!DOCTYPE HTML>
   <html>
    <head>
    <script>
      let openFile = function(event) {
        let input = event.target;
        let reader = new FileReader();
        reader.onload = function(){
          let text = reader.result;
          let node = document.getElementById('output');
                node.innerText = text;
          console.log(reader.result.substring(0, 200));
        };
        reader.readAsText(input.files[0]);
      };
    </script>
    </head>
    <body>
    <input type='file' accept='text/plain' onchange='openFile(event)'><br>
    <div id='output'>
    </div>
    </body>
    </html>

我需要加载文档,然后仅显示我需要的字符串-名称和网址,例如:

文档示例:

#NAME:Elis:
http://elis.com
#NAME:Emma:
http://emma.com

显示

<a href=http://elis.com>Elis</a>
<a href=http://emma.com>Emma</a>

2 个答案:

答案 0 :(得分:1)

let openFile = function(event) {
  let input = event.target;
  let reader = new FileReader();
  reader.onload = function() {
    let text = reader.result;
    let node = document.getElementById('output');
    // node.innerText = text;

    var resultText = "";
    lines = reader.result.split(/\r\n|\r|\n/);
    for (let i = 0; i < lines.length - 1; i += 2) {
      var matches = lines[i].match(/\#NAME:([^:]+)/);
      resultText += `<a href="${lines[i+1].trim()}">${matches[1].trim()}</a>\n`;
    }
    // innerText here only for demonstration purpose
    // use innerHTML for working code instead
    node.innerText = resultText;
    // node.innerHTML = resultText
  };
  reader.readAsText(input.files[0]);
};
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<div id='output'>

答案 1 :(得分:0)

var str = `#NAME:Elis:
http://elis.com
#NAME:Emma:
http://emma.com`;

const makeUpHrefs = str => {
    let arr = str.split(/\n#/);
    arr = arr.map(row => '<a href="' + row.match(/\n(.*)/)[1] + '">' + row.match(/NAME:(.*?):/)[1] + '</a>');
    return arr;
};

因此,makeUpHrefs(str)将返回html的数组:

<a href="http://elis.com">Elis</a>
<a href="http://emma.com">Emma</a>