javascript 通过新行(包括空行)将textarea中的文本拆分为javascript数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28241954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Splitting text in textarea by new lines (including empty lines) into javascript array
提问by Andres SK
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 linesas 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."]
[“我喜欢吃冰淇淋。狗的速度很快。”,“ ”,“前一行仅由空格组成。”,“最后3行是空的。”,“最后一行。”]
What it shouldbe:
它应该是什么:
["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."]
[“我喜欢吃冰淇淋。狗的速度很快。”,“”,“前一行仅由空格组成。”,“”,“”,“”,“最后3行是空的。”,“” , “最后一行。”]
回答by geedubb
Your .split
will include \n, but when line
is falsey you can just push an empty string...
你.split
将包括\n,但是什么时候line
是假的,你可以只推一个空字符串......
$(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
这是一个工作示例: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):
或者就像上面的评论所暗示的那样(我假设你的例子已经简化,你需要在.each
循环中做其他事情):
var lines = $('#data').val().split(/\n/);