如何使用javascript解析文本文件 [英] How can I parse a text file using javascript

查看:503
本文介绍了如何使用javascript解析文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是使用javascript读取文本文件。有用。
但是,我只是想阅读部分内容。
例如,文件的内容是:Hello world!
我只想显示你好。
我试过函数 split(),但它只适用于字符串。我不知道如何在此处插入。

The code below is to read a text file using javascript. it works. However, I just want to read part of the content. For example, the content of the file is :"Hello world!" I just want to display "Hello". I tried function split(), but it only works on strings. I don't know how to insert it here.

 var urls = ["data.txt"];

function loadUrl() {
    var urlToLoad = urls[0];
    alert("load URL ... " + urlToLoad);
    browser.setAttributeNS(xlinkNS, "href", urlToLoad);
}

谢谢!!!

推荐答案

如果我正确理解了您的需要,请尝试阅读单独的单词。
创建一个内容为hello world的文件,并使用示例脚本浏览到该文件。
输出为你好。

Try this to read separate words if I understood correctly what you need. Create a file with the contents "hello world" and browse to it with the example script. The output is "hello".

<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
  function readSingleFile(evt) {
    var f = evt.target.files[0];   
    if (f) {
      var r = new FileReader();
      r.onload = function(e) { 
          var contents = e.target.result;             
          var ct = r.result;
          var words = ct.split(' ');            
          alert(words[0]);
      }
      r.readAsText(f);
    } else { 
      alert("Failed to load file");
    }
  }

  document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</head>
<body>
</body>
</html>

由于javascript对安全性的限制,直接读取必须使用ajax请求。
此代码shoudl执行请求的操作:

Reading directly has to be with an ajax request due to the javascript restrictions regarding safety. This code shoudl perform the requested operation:

<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
  if(xmlhttp.status==200 && xmlhttp.readyState==4){    
    var words = xmlhttp.responseText.split(' ');
    alert(words[0]);
  }
}
xmlhttp.open("GET","FileName.txt",true);
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>

这篇关于如何使用javascript解析文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆