Home > Back-end >  Parsing text area line that comma separated using Jquery or Js
Parsing text area line that comma separated using Jquery or Js

Time:01-08

I have a textarea with data like this (UserId,Name,Gender), and I want to parsing that data

<textarea  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>

i want all IDs only , Names only And i want to get Names&Gender from text area above , i tried to separated this data but if failed . This my JS code :

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

CodePudding user response:

Split your trimmed string by newlines to create an array of strings.
Then, depending on the desired output use Array.prototype.map() or 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
// Log only names
list.forEach((user) => {
  console.log(user.name);
});

// 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  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>

CodePudding user response:

You could also do it like this.

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  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>


EDIT

If you want to replace the contents of the textarea with specific values from the processed array of objects (results, in my example), you could do that like this.

Please note that you do not need extra textareas, like in the following example. I am using them to show you what you would get for different combinations. In reality, you would replace the contents of the #data element with the new content.

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);
    }
  }
}

// This doesn't have to be here, you can use the logic in the loop above
// which would a better, more efficient way of doing it
// I'm doing this separately, so you can better understand how it works
// That's why there are 6 additional textareas - in reality, you would
// change the contents of your original textarea

var tmpNames = "", tmpIdsNames = "",
tmpGenders = "", tmpIdsGenders = "",
tmpNamesGenders = "", tmpIdsNamesGenders = "";

for(var i = 0; i < results.length; i  ) {
    tmpNames  = results[i].firstName  "\r\n";
  tmpIdsNames  = results[i].id   ","   results[i].firstName   "\r\n";
  tmpGenders  = results[i].gender   "\r\n";
  tmpIdsGenders  = results[i].id   ","   results[i].gender   "\r\n";
  tmpNamesGenders  = results[i].firstName   ","   results[i].gender   "\r\n";
  tmpIdsNamesGenders  = results[i].id   ","   results[i].firstName   ","   results[i].gender   "\r\n";
}

$("#justNames").val(tmpNames);
$("#idsNames").val(tmpIdsNames);
$("#justGenders").val(tmpGenders);
$("#idsGenders").val(tmpIdsGenders);
$("#namesGenders").val(tmpNamesGenders);
$("#idsNamesGenders").val(tmpIdsNamesGenders);
textarea {
  width: 100%;
}
.results {
  display: inline-block;
  width: 30%;
  margin-right: 15px;
}
.results textarea {
  min-height: 75px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label style="display:block; width:100%">Original data
<textarea  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>
</label>
<label >Just names
<textarea style="display:block" id="justNames" name="justNames"></textarea>
</label>
<label >IDs and names
<textarea style="display:block" id="idsNames" name="idsNames"></textarea>
</label>
<label >Just genders
<textarea style="display:block" id="justGenders" name="justGenders"></textarea>
</label>
<label >IDs and genders
<textarea style="display:block" id="idsGenders" name="idsGenders"></textarea>
</label>
<label >Names and genders
<textarea style="display:block" id="namesGenders" name="namesGenders"></textarea>
</label>
<label >IDs, names and genders
<textarea style="display:block" id="idsNamesGenders" name="idsNamesGenders"></textarea>
</label>

You can also experiment with this fiddle.

CodePudding user response:

See String.prototype.split() and Array.prototype.map().

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