将textareas字符串值转换为由新行分隔的JavaScript数组
我有 textarea
,用户最多可以写1000个字符。我需要获取 jQuery('#textarea')。val()
并创建一个数组,其中每个项目都是 textarea的一行
的价值。这意味着:
I have a textarea
where 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中的一条很好的行。
这是另一行。
(让我们假设这一行是空的 - 应该被忽略)。
有人在上面留下了2个以上的新行。
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.
应转换为JavaScript数组:
Should be converted to a JavaScript array:
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.';
这样他们就可以轻松地 imploded for querystring(这是提供者要求的qs格式):
That way they can be easily imploded for to querystring (this is the qs format required by the provider):
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."]
我试过了 phpjs explode()
和 string.split(\ n)
接近但他们没有处理额外的新线(也就是断线)。有什么想法?
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?
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]));
}
}
请注意 String.prototype并非所有平台都支持.split
,因此jQuery提供了 $ .split()
。它只是修剪字符串末尾周围的空格。
Note that String.prototype.split
is not supported on all platforms, so jQuery provides $.split()
instead. It simply trims whitespace around the ends of a string.
$.trim(" asd \n") // "asd"