Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  153] [ 1]  / answers: 1 / hits: 41029  / 13 Years ago, mon, december 12, 2011, 12:00:00

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?


More From » jquery

 Answers
36

String.prototype.split() is sweet.



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]));
}
}


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


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


[#88599] Saturday, December 10, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;