How to create an array with a list of strings

I have a generated list similar to this

196-1526, 85-651, 197-1519

I need an array like this. Each node has two parts. I only need the first part of each node in one array.

196, 85, 197

I already have this code which generates 196

str.substr(0,str.indexOf('-'));

      

+3


source to share


5 answers


You can use the following:



'196-1526, 85-651, 197-1519'.replace(/-\d+(,|$)/g, '').split(/\s/)

      

+3


source


if it's an array

var myarray = ["196-1526", "85-651", "197-1519"];
var newarray = [];
var i = 0;
for(i = 0; i < myarray.length; i++){
  var mnode = myarray[i].split("-");
   newarray.push(mnode[0].trim());
}

      

and if it is a string



var myarray = "196-1526, 85-651, 197-1519".split(",");
var newarray = [];
var i = 0;
for(i = 0; i < myarray.length; i++){
  var mnode = myarray[i].split("-");
   newarray.push(mnode[0].trim());
}

      

Demo : http://jsfiddle.net/Dbbc8/

+2


source


If the input is a string, you can use split () and push () , similar to this:

var x = "196-1526, 85-651, 197-1519"
var y = x.split(',');

var myArray = [];

for(i = 0; i < y.length; i++){
    myArray.push(y[i].split('-')[0].trim());
}

      


DEMO - Usingsplit()

andpush()


+2


source


try this code using split

var text='196-1526, 85-651, 197-1519';
    var splittedtext=text.split(',');
    var numbers=new Array(); 
    for(var i=0;i<splittedtext.length;i++)
    {
        var furthsplit=splittedtext[i].split('-');
        numbers[i]=furthsplit[0];
    }
    alert(numbers);

      

0


source


var pairs = str.split(", ");
var values = [];

for (var i=0; i< pairs.length; i++) {
    values.push(pairs[i].substr(0, pairs[i].indexOf('-')));
}

      

0


source







All Articles