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...
Asked
Active
Viewed 6.0k times
6 Answers
65
This should work (tested in Firefox and Google Chrome):
var arrayOfLines = $('#textAreaID').val().split('\n');

Daniel Vassallo
- 337,827
- 72
- 505
- 443
-
4It should be `$('#textArea').val().split('\n')`, the jQuery object doesn't have a `value` property. – Christian C. Salvadó Feb 19 '10 at 21:21
-
@CMS - or even $('#textArea')[0].value.split('\n') :) – Russ Cam Feb 19 '10 at 21:25
-
@CMS: Oops. Thanks for noting. – Daniel Vassallo Feb 19 '10 at 21:44
22
Cross-platform way:
var area = document.getElementById("area");
var lines = area.value.replace(/\r\n/g,"\n").split("\n");

KIM Taegyoon
- 1,917
- 21
- 18
4
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);

Dexygen
- 12,287
- 13
- 80
- 147
-
To clarify, is this using the fact that an empty string is false-y in JavaScript? – IMP1 Jan 24 '20 at 13:27
-
0
You could try this function :
function textToArray(){
var someArray = [];
var nameList = $("#txtArea").val();
$.each(nameList.split(/\n/), function (i, name) {
// empty string check
if(name != ""){
someArray.push(name);
}
});
taken from : CONVERT TEXTAREA CONTENT TO AN ARRAY USING JQUERY

Yasser Shaikh
- 46,934
- 46
- 204
- 281
0
This method worked well:
var textArea = document.getElementById("textAreaId");
var arrayFromTextArea = textArea.value.split(String.fromCharCode(10));

סטנלי גרונן
- 2,917
- 23
- 46
- 68

fatih bülbül
- 21
- 3