Javascript: Convert textarea into an array
Asked Answered
I

6

38

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...

Ivatts answered 19/2, 2010 at 21:13 Comment(0)
V
68

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

var arrayOfLines = $('#textAreaID').val().split('\n');
Vanover answered 19/2, 2010 at 21:14 Comment(3)
It should be $('#textArea').val().split('\n'), the jQuery object doesn't have a value property.Turki
@CMS - or even $('#textArea')[0].value.split('\n') :)Cauley
@CMS: Oops. Thanks for noting.Vanover
L
22

Cross-platform way:

var area = document.getElementById("area");             
var lines = area.value.replace(/\r\n/g,"\n").split("\n");
Lucre answered 27/8, 2015 at 4:29 Comment(0)
H
13
var stringArray = document.getElementById('textarea').value.split('\n');
He answered 19/2, 2010 at 21:22 Comment(0)
J
4

I like the "cross-platform way" answer best (https://mcmap.net/q/403844/-javascript-convert-textarea-into-an-array) 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);
Joung answered 24/1, 2020 at 13:20 Comment(2)
To clarify, is this using the fact that an empty string is false-y in JavaScript?Faso
@Faso PreciselyJoung
B
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

Beeck answered 10/4, 2013 at 17:16 Comment(0)
P
0

This method worked well:

var textArea = document.getElementById("textAreaId");
var arrayFromTextArea = textArea.value.split(String.fromCharCode(10));
Plasmagel answered 9/12, 2018 at 8:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.