将 textareas 字符串值转换为由新行分隔的 JavaScript 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8479053/
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
convert textareas string value to JavaScript array separated by new lines
提问by Andres SK
I have a textareawhere the user can write up to 1000 characters. I need to get the jQuery('#textarea').val()and create an array where each item is a line of the textarea's value. That means:
我有一个textarea用户最多可以写 1000 个字符的地方。我需要获取jQuery('#textarea').val()并创建一个数组,其中每个项目都是textarea's 值的一行。这意味着:
This is a nice line inside the textarea.
This is another line.
(let's asume this line is empty - it should be ignored).
Someone left more than 2 new lines above.
这是 textarea 内的一条漂亮的线。
这是另一条线。
(让我们假设这一行是空的——它应该被忽略)。
有人在上面留下了 2 个以上的新行。
Should be converted to a JavaScript array:
应转换为 JavaScript 数组:
var texts = [];
text[0] = 'This is a nice line inside the textarea.';
text[1] = 'This is another line.';
text[2] = 'Someone left more than 2 new lines above.';
That way they can be easily implodedfor to querystring (this is the qs format required by the provider):
这样它们就可以很容易地被分解为查询字符串(这是提供者要求的 qs 格式):
example.com/process.php?q=["This is a nice line inside the textarea.","This is another line.","Someone left more than 2 new lines above."]
I tried both the phpjs explode()and string.split("\n")approaches but they doesn't take care of the extra new lines (aka line breakes). Any ideas?
我尝试了phpjsexplode()和string.split("\n")方法,但他们没有处理额外的新行(又名换行符)。有任何想法吗?
回答by Alex Wayne
String.prototype.split()is sweet.
String.prototype.split()是甜的。
var lines = $('#mytextarea').val().split(/\n/);
var texts = [];
for (var i=0; i < lines.length; i++) {
// only push this line if it contains a non whitespace character.
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
Note that String.prototype.splitis not supported on all platforms, so jQuery provides $.split()instead. It simply trims whitespace around the ends of a string.
请注意,String.prototype.split并非所有平台都支持,因此 jQuery 提供$.split()。它只是修剪字符串末端周围的空白。
$.trim(" asd \n") // "asd"
Check it out here: http://jsfiddle.net/p9krF/1/
在这里查看:http: //jsfiddle.net/p9krF/1/
回答by Abdul Munim
Use splitfunction:
使用split功能:
var arrayOfLines = $("#input").val().split("\n");
回答by Phil Klein
var split = $('#textarea').val().split('\n');
var lines = [];
for (var i = 0; i < split.length; i++)
if (split[i]) lines.push(split[i]);
return lines;
回答by ShankarSangoli
Try this
尝试这个
var lines = [];
$.each($('textarea').val().split(/\n/), function(i, line){
if(line && line.length){
lines.push(line);
}
});

