Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 views
in Technique[技术] by (71.8m points)

jquery - convert textareas string value to JavaScript array separated by new lines

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(" ") approaches but they doesn't take care of the extra new lines (aka line breakes). Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

String.prototype.split() is sweet.

var lines = $('#mytextarea').val().split(/
/);
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  
") // "asd"

Check it out here: http://jsfiddle.net/p9krF/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...