将 textareas 字符串值转换为以换行符分隔的 JavaScript 数组
我有一个 textarea
,用户最多可以在其中写入 1000 个字符。我需要获取 jQuery('#textarea').val() 并创建一个数组,其中每个项目都是 textarea
值的一行。这意味着:
这是文本区域内的一行漂亮的线。
这是另一行。
(我们假设这一行是空的 - 它应该被忽略)。
有人在上面留下了超过 2 行新行。
应该转换为 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.';
这样它们就可以轻松 内爆 为查询字符串(这是提供商要求的 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."]
我尝试了 phpjs explode()
< /a> 和string.split("\n")
方法,但它们不处理额外的新行(也称为换行符)。有什么想法吗?
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:
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
String.prototype.split()
很不错。请注意,并非所有平台都支持
String.prototype.split
,因此 jQuery 提供了$.split()
。它只是修剪字符串末端周围的空白。在这里查看:http://jsfiddle.net/p9krF/1/
String.prototype.split()
is sweet.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.Check it out here: http://jsfiddle.net/p9krF/1/
使用 split 函数:
Use
split
function:试试这个
Try this