And*_* SK 25 javascript arrays string jquery newline
我有一个textarea用户可以写最多1000个字符的地方.我需要得到jQuery('#textarea').val()并创建一个数组,其中每个项目都是一行textarea的值.这意味着:
这是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.';
Run Code Online (Sandbox Code Playgroud)
这样,他们可以很容易地被引爆的查询字符串来(这是由供应商所要求的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."]
Run Code Online (Sandbox Code Playgroud)
我尝试了phpjsexplode()和string.split("\n")方法,但他们没有处理额外的新行(也就是换行符).有任何想法吗?
Ale*_*yne 33
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]));
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,String.prototype.split并非所有平台都支持,因此jQuery提供了相应的功能$.split().它只是修剪字符串末端周围的空白.
$.trim(" asd \n") // "asd"
Run Code Online (Sandbox Code Playgroud)
在这里查看:http://jsfiddle.net/p9krF/1/
使用split功能:
var arrayOfLines = $("#input").val().split("\n");
Run Code Online (Sandbox Code Playgroud)