Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Convert textarea into an array

How would you go about breaking up a textarea value into an array, based on the end of line separation? Use of jQuery is cool by me...

like image 553
Matrym Avatar asked Feb 19 '10 21:02

Matrym


4 Answers

This should work (tested in Firefox and Google Chrome):

var arrayOfLines = $('#textAreaID').val().split('\n');
like image 93
Daniel Vassallo Avatar answered Oct 17 '22 09:10

Daniel Vassallo


Cross-platform way:

var area = document.getElementById("area");             
var lines = area.value.replace(/\r\n/g,"\n").split("\n");
like image 30
KIM Taegyoon Avatar answered Oct 17 '22 10:10

KIM Taegyoon


var stringArray = document.getElementById('textarea').value.split('\n');
like image 13
Eric Avatar answered Oct 17 '22 10:10

Eric


I like the "cross-platform way" answer best (https://stackoverflow.com/a/32240738/34806) as I've grappled with input from a Mac in the past. Nevertheless I think most of the existing answers could benefit from an additional step.

Specifically, what if some lines are empty? The following will filter out such lines so that we wind up with a "compact" array rather than a "sparse" one (or at least, rather than one with elements containing no values)

var area = document.getElementById("area");             
var lines = area.value.replace(/\r\n/g,"\n").split("\n").filter(line => line);
like image 4
Dexygen Avatar answered Oct 17 '22 09:10

Dexygen