Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array elements containing carriage return

Start with an array of strings, some of which feature carriage returns:

var valArray = ["Saab","Volvo","BMW\nHonda\nAudi","Mazda"];

What I want to do is get rid of the carriage return, splitting the string into as many elements as there are carriage returns +1:

["Saab","Volvo","BMW","Honda","Audi","Mazda"];

What I get with .split:

valArray.split("\n");
["Saab","Volvo",["BMW","Honda","Audi"],"Mazda"];

Any suggestions?

like image 778
Temperedsoul Avatar asked Jul 26 '26 23:07

Temperedsoul


1 Answers

Map the items to arrays after splitting the carriage returns, then flatten the arrays by applying concat:

var valArray = ["Saab","Volvo","BMW\nHonda\nAudi","Mazda"];

var result = [].concat.apply([], valArray.map(function(item) {
  var items = item.split('\n');
  
  return items;
}));

console.log(result);

And another method without a loop:

var valArray = ["Saab","Volvo","BMW\nHonda\nAudi","Mazda"];

var result = valArray.join(',').split('\n').join(',').split(',');

console.log(result);
like image 125
Ori Drori Avatar answered Jul 29 '26 12:07

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!