javascript 使用Jquery或Js解析逗号分隔的文本区域行

wztqucjr  于 2023-01-07  发布在  Java
关注(0)|答案(3)|浏览(153)

我有一个文本区域,其中包含这样的数据(UserId、Name、Gender),我想解析这些数据

<textarea class="form-control" id="data" rows="5" cols="10" placeholder="ID's Phones Number:" name="msg">097544,markd amm,male
731490,Hossam Hassan,male
130578,Kamal Eldin,male
87078148,Muhammad Ahmad Atia,male
932484,Alia AlHorria,female
093779,Yaser Hadidi,male
39393,Soka Dą,female
</textarea>

我只想所有的ID,名称只和我想从上面的文本区名称和性别,我试图分开这个数据,但如果失败。这是我的JS代码:

var data = $('#data').val();
  console.log(fbdata[0]);
u5rb5r59

u5rb5r591#

用换行符分割裁剪后的字符串以创建一个字符串数组。
然后,根据所需的输出使用Array.prototype.map()Array.prototype.reduce()

const elData = document.querySelector("#data");

const str = elData.value.trim();
const lines = str.split(/\n/);

// Example 1: create array or data objects

const list = lines.map(str => {
  const [id, name, gender] = str.split(",");
  return {id, name, gender};
});

// console.log(list); // get 'em all
console.log(list[1]); // get by index

// example 2: create Object of items - by ID

const listById = lines.reduce((acc, str) => {
  const [id, name, gender] = str.split(",");
  acc[id]= {id, name, gender};
  return acc;
}, {});

// console.log(listById); // get 'em all
console.log(listById[731490]) // Get specific by ID
<textarea class="form-control" id="data" name="msg">097544,markd amm,male
731490,Hossam Hassan,male
130578,Kamal Eldin,male
87078148,Muhammad Ahmad Atia,male
932484,Alia AlHorria,female
093779,Yaser Hadidi,male
39393,Soka Dą,female
</textarea>
tp5buhyn

tp5buhyn2#

请参见String.prototype.split()Array.prototype.map()

var data = $('#data').val().split("\n").map(line => line.split(",")[0]);
// ['097544', '731490', '130578', '87078148', '932484', '093779', '39393']
dgenwo3n

dgenwo3n3#

你也可以这样做。

var results = [];
var data = $('#data').val().trim();

if(data) {
  // Create an array by splitting the textarea.value by newline
  data = data.split(/\r?\n/);
 
  // Loop through indivdual rows, and split by comma / ,
  for(var i = 0; i < data.length; i++) {
    var temp = data[i].trim();

    if(temp) {
      // Create an array from the values in the current line
      temp = temp.split(",");

      // Separate the first and last names
      var pairs = temp[1].split(/ (.*)/s);

      var personsObj = {};
      personsObj.id = temp[0];
      personsObj.firstName = pairs[0].trim();
      personsObj.lastName = pairs[1].trim();
      personsObj.gender = temp[2].trim();
      
      results.push(personsObj);
    }
  }
}

console.log(results);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="form-control" id="data" rows="5" cols="10" placeholder="ID's Phones Number:" name="msg">097544,markd amm,male
731490,Hossam Hassan,male
130578,Kamal Eldin,male
87078148,Muhammad Ahmad Atia,male
932484,Alia AlHorria,female
093779,Yaser Hadidi,male
39393,Soka Dą,female
</textarea>

相关问题