Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting text in textarea by new lines (including empty lines) into javascript array

I'm trying to split the text inside Splitting textarea data by new lines. My current code works, except for a small requirement: The resulting array must include empty lines as well.

<script>
$(function(){
    var lines = [];
    $.each($('#data').val().split(/\n/), function(i, line){
        if(line){
            lines.push(line);
        }
    });
    console.log(lines);
});
</script>


<textarea id="data">
I like to eat icecream. Dogs are fast.

The previous line is composed by spaces only.



The last 3 lines are empty.

One last line.
</textarea>

The current result is:

["I like to eat icecream. Dogs are fast.", " ", "The previous line is composed by spaces only.", "The last 3 lines are empty.", "One last line."]

What it should be:

["I like to eat icecream. Dogs are fast.", " ", "The previous line is composed by spaces only.", "", "", "", "The last 3 lines are empty.", "", "One last line."]

like image 612
Andres SK Avatar asked Jan 30 '15 18:01

Andres SK


2 Answers

Your .split will include \n, but when line is falsey you can just push an empty string...

$(function(){
    var lines = [];
    $.each($('#data').val().split(/\n/), function(i, line){
        if(line){
            lines.push(line);
        } else {
            lines.push("");
        }
    });
    console.log(lines);
});

Here is a working example : JSFiddle

Output:

["I like to eat icecream. Dogs are fast.", 
"",  "The previous line is composed by spaces only.",  
"",  "",  "", 
"The last 3 lines are empty.",  
"",  "One last line."]

Or simply as comment above suggests (I had assumed that your example had been simplified and you need to do something else in the .each loop):

var lines = $('#data').val().split(/\n/);

JS Fiddle

like image 153
geedubb Avatar answered Sep 17 '22 10:09

geedubb


In addition to geedubb's answer if you prefer to avoid using the backslash for encoding reasons:

var lines = $('#data').val().split(String.fromCharCode(10));
like image 25
RafaSashi Avatar answered Sep 17 '22 10:09

RafaSashi