[英]convert textareas string value to JavaScript array separated by new lines
I have a textarea
where the user can write up to 1000 characters. 我有一个textarea
,用户最多可以写1000个字符。 I need to get the jQuery('#textarea').val()
and create an array where each item is a line of the textarea
's value. 我需要获取jQuery('#textarea').val()
并创建一个数组,其中每个项都是textarea
值的一行。 That means: 这意味着:
This is a nice line inside the textarea. 这是textarea内部的一个很好的路线。
This is another line. 这是另一条线。
(let's asume this line is empty - it should be ignored). (让我们假设这一行是空的 - 应该被忽略)。
Someone left more than 2 new lines above. 有人在上面留下了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 imploded for 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). 我尝试了phpjs explode()
和string.split("\\n")
方法,但他们没有处理额外的新行(也就是换行符)。 Any ideas? 有任何想法吗?
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.split
is not supported on all platforms, so jQuery provides $.split()
instead. 请注意,并非所有平台都支持String.prototype.split
,因此jQuery提供了$.split()
。 It simply trims whitespace around the ends of a string. 它只是修剪字符串末端周围的空白。
$.trim(" asd \n") // "asd"
Check it out here: http://jsfiddle.net/p9krF/1/ 在这里查看: http : //jsfiddle.net/p9krF/1/
使用split
功能:
var arrayOfLines = $("#input").val().split("\n");
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;
Try this 试试这个
var lines = [];
$.each($('textarea').val().split(/\n/), function(i, line){
if(line && line.length){
lines.push(line);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.