问题描述
我有一个 textarea
,用户最多可以在其中写入 1000 个字符.我需要获取 jQuery('#textarea').val()
并创建一个数组,其中每个项目都是 textarea
值的一行.这意味着:
这是 textarea 中的一个不错的行.
这是另一行.
(假设这一行是空的 - 它应该被忽略).
有人在上面留下了 2 行以上的新行.
应该转换成JavaScript数组:
var texts = [];text[0] = '这是 textarea 中的一个不错的行.';text[1] = '这是另一行.';text[2] = '有人在上面留下了超过 2 行的新行.';
这样他们可以很容易地内爆到查询字符串(这是所需的qs格式由提供者提供):
example.com/process.php?q=["这是文本区域内的一行不错的行.","这是另一行.","有人在上面留下了超过 2 行新行."]
我尝试了 phpjs explode()
和 string.split("\n")
方法,但它们不处理额外的新行(又名换行符).有什么想法吗?
String.prototype.split()
很贴心.
var lines = $('#mytextarea').val().split(/\n/);var 文本 = [];for (var i=0; i
请注意,String.prototype.split
并非在所有平台上都受支持,因此 jQuery 提供了 $.split()
代替.它只是修剪字符串两端的空格.
$.trim(" asd \n")//"asd"
在这里查看:http://jsfiddle.net/p9krF/1/>
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:
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.';
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."]
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()
is sweet.
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. It simply trims whitespace around the ends of a string.
$.trim(" asd \n") // "asd"
Check it out here: http://jsfiddle.net/p9krF/1/
这篇关于将 textareas 字符串值转换为由新行分隔的 JavaScript 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!