textarea的值转换为JavaScript数组(以换行分隔) [英] Convert textarea value to javascript array (separated by new lines)

查看:1478
本文介绍了textarea的值转换为JavaScript数组(以换行分隔)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个textarea,用户可以写入多达1000个字符。我需要获得$('#textarea的')。VAL(),并创建一个数组,其中每个产品textarea的价值的一条线。这意味着:

I have a textarea where the user can write up to 1000 characters. I need to get the $('#textarea').val() and create an array where each item is a line of the textarea's value. That means:

这是文本区域内一个漂亮的线。

This is a nice line inside the textarea.

这是另一条线路。

(让我们asume这条线是空的 - 它应该被忽略)。

(let's asume this line is empty - it should be ignored).

左上面有人超过2个新行。

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.';

这样,他们可以很容易地内爆获取到的查询字​​符串(这是由供应商所要求的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 =这是textarea的内一个漂亮的线。,这是另一条线。,左上面有人超过2个新的生产线。]

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爆炸()并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 (if any). 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提供 $。斯普利特()来代替。它简单地修剪围绕一个串的端部的空白

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"

看看这里: http://jsfiddle.net/p9krF/1/

这篇关于textarea的值转换为JavaScript数组(以换行分隔)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆