最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can i convert a .txt document into an array in JavaScript? - Stack Overflow

programmeradmin0浏览0评论

I am trying to convert a .txt deocument into an array.

The document has names in it and is structured like this:

Name1
Name2
Name3

The program has to read the lines and the output should be

["Name1","Name2","Name3"].

I have looked all over the internet, but most solutions just involve node.js, which i cannot install on the puter I need the software on, or some plex xmlhttp code I do not understand. I am just looking for a simple solution.

Can anybody help?

I am trying to convert a .txt deocument into an array.

The document has names in it and is structured like this:

Name1
Name2
Name3

The program has to read the lines and the output should be

["Name1","Name2","Name3"].

I have looked all over the internet, but most solutions just involve node.js, which i cannot install on the puter I need the software on, or some plex xmlhttp code I do not understand. I am just looking for a simple solution.

Can anybody help?

Share Improve this question asked Aug 23, 2021 at 18:34 PhDaherPhDaher 411 silver badge2 bronze badges 3
  • It's not clear what you're asking. You'll need some mechanism to read the file. What it is depends on your server setup and your preferences. – isherwood Commented Aug 23, 2021 at 18:36
  • 1 You can't use node, so where are you running the javascript? A browser? – Nick Commented Aug 23, 2021 at 18:36
  • 1 Or is this just something you'll run locally? Please see How to Ask and provide more information. – isherwood Commented Aug 23, 2021 at 18:38
Add a ment  | 

3 Answers 3

Reset to default 3

To fetch the file contents you can use the fetch API in js which is pretty simple ( just pass the file url inside as parameter ) and clean to use .. Moreover to solve your issue regarding converting the text extracted from the file into an array you can use string.split method !

async function getFile(fileURL){
    let fileContent = await fetch(fileURL);
    fileContent = await  fileContent.text();
    return fileContent;
}

// Passing file url 
getFile('file.txt').then(content =>{
   // Using split method and passing "\n" as parameter for splitting
   let array =  content.trim().split("\n");
   console.log(array);
}).catch(error =>{
    console.log(error);
});

After getting text you can use string.split method and when used with .trim() method will remove extra spaces too !

Read MDN docs for information about fetch API

You could create an <input type="file"> for opening a file from your puter, read it with a FileReader and split() the result by newline (with for example regex /\r?\n/) to bee an array of words.

const openFile = (e) => {
  const reader = new FileReader(); // filereader
  reader.readAsText(e.target.files[0]); // read as text
  reader.onload = () => {
    const text = reader.result;
    const result = text.split(/\r?\n/); // split on every new line
    console.log(result); // do something with array
  };
};
<input type='file' accept='text/plain' onchange='openFile(event)'>

You can try it out in this fiddle.

You could also acplish this in another (newer) way as suggested in the ments, using .then.

const openFile = (e) => {
  e.target.files[0].text().then((t) => {
    const oute = t.split(/\r?\n/);
    console.log(oute);
  });
};
<input type='file' accept='text/plain' onchange='openFile(event)'>

Since you won't use node, I am assuming you're running your code on a browser. And the file from an <input type="file"/>

<html>
  <input type="file" id="inputFile">

  <script>
   const inputFile = document.querySelector('#inputFile');

   inputFile.addEventListener('change', () => {
     const fileReader = new FileReader();
     fileReader.onload = e => {
       const array = e.target.result.split('\n');
       console.log(array);
     };
     fileReader.readAsText(inputFile.files[0], 'UTF-8');
   });
  </script>
</html>
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>