用新行(包括空行)将textarea中的文本拆分为javascript数组 [英] Splitting text in textarea by new lines (including empty lines) into javascript array
问题描述
我正在尝试通过换行来拆分textarea数据中的文本.我的当前代码有效,但有一个小要求:生成的数组还必须包含空行.
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>
当前结果是:
[我喜欢吃冰淇淋.狗很快.",",上一行仅由空格组成.",最后三行是空的.",最后一行."]
["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行是空的." ,",最后一行".]
["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."]
推荐答案
您的.split
将包含\ n,但是当line
为false时,您可以压入一个空字符串...
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);
});
这是一个有效的示例: JSFiddle
Here is a working example : JSFiddle
输出:
["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."]
或者就像上面的注释所暗示的那样(我假设您的示例已经简化,并且您需要在.each
循环中做其他事情):
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/);
这篇关于用新行(包括空行)将textarea中的文本拆分为javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!