将textareas字符串值转换为由新行分隔的JavaScript数组 [英] convert textareas string value to JavaScript array separated by new lines

查看:185
本文介绍了将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"

点击此处: http://jsfiddle.net/p9krF/1/

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

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