Temperedsoul Temperedsoul - 1 year ago 93
Javascript Question

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:


What I get with .split:


Any suggestions?

Answer Source

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;


And another method without a loop:

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

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download