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

╄→гoц情女王★ 提交于 2019-12-24 12:09:37

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/28241954/splitting-text-in-textarea-by-new-lines-including-empty-lines-into-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!