Reputation: 11745
I have a textarea in which the user enters the following data:
I want to read the data and store the values before the colon in an array and the values after the colon in another array. Please note that the user may not enter values after the colon like in case 3 above. In such case, the value must be stored in the first array as if it is before the colon.
How can I do that using jquery?
Upvotes: 1
Views: 468
Reputation: 26116
Something like this:
var txt = $('#your_array').text();
var lines = txt.split('\n');
var data = new Array();
for(var i=0;i<lines.length;i++){
var o = {};
var array1 = txt.split(':');
o.name = array1[0];
if(array1.length > 1){
var array2 = array1[1].split(',');
o.number = array2[0];
if(array2.length > 1){
o.location = array2[1];
}
}
data.push(o);
}
/*
data = [
{ name: "Paul", number: "Nine", location: "Rome" },
{ name: "Jenny", number: "Five", location: "India" },
{ name: "Bob" }
];
*/
Upvotes: 0
Reputation: 187110
You can use text() and split
var arrDetails = $("#txtareaid").text().split(':');
//arrDetails[0] will get the string before colon
//arrDetails[1] will get the string after colon
If there is no colon then arrDetails[1]
will be undefined
Upvotes: 1