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."]
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
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));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With