首页 > 解决方案 > 如何将文本文件作为数组读取

问题描述

我有一个如下所示的文本文件(不是 json):

['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']

我如何读取它并放入 2 个数组:['a'、'b'、'c'、'd'] 和 ['e'、'f'、'g'、'h']?

我正在使用它来读取文件:

jQuery.get('filename.txt', function(data){
 alert(data);
});

标签: javascriptarraystext

解决方案


解决方案1:

  1. \r\n用 multiline( )分割字符串
  2. 循环遍历拆分的字符串数组并将单引号替换为双引号以使其成为有效的 JSON 字符串
  3. 解析 JSON 字符串JSON.parse

const exampleData = `['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']`;

const multiLineTextToArray = (txt) => {
  return (txt.match(/[^\r\n]+/g) || []).map((line) => {
    // replace single quote with double quote to make it proper json string
    // then parse the string to json
    return JSON.parse(line.replace(/\'/g, '\"'));
  });  
};

/**
jQuery.get('filename.txt', function(data){
 alert(multiLineTextToArray(data));
});
*/

// example
console.log(multiLineTextToArray(exampleData));

解决方案 2:构造一个有效的 JSON 数组

  1. \r\n用 ','替换 multiline( )
  2. 用双引号替换单引号
  3. []
  4. 解析 JSON 字符串JSON.parse

const exampleData = `['a', 'b', 'c', 'd']
['e', 'f', 'g', 'h']`;

const multiLineTextToArray = (txt) => {
  return JSON.parse(`[${txt.replace(/[\r\n]+/g, ',').replace(/\'/gm, '\"')}]`);
};

/**
jQuery.get('filename.txt', function(data){
 alert(multiLineTextToArray(data));
});
*/

// example
console.log(multiLineTextToArray(exampleData));


推荐阅读