convert textareas string value to JavaScript array separated by new lines

后端 未结 4 1608
孤城傲影
孤城傲影 2020-12-08 10:33

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

相关标签:
4条回答
  • 2020-12-08 10:48
    var split = $('#textarea').val().split('\n');
    var lines = [];
    for (var i = 0; i < split.length; i++)
        if (split[i]) lines.push(split[i]);
    return lines;
    
    0 讨论(0)
  • 2020-12-08 10:59

    Use split function:

    var arrayOfLines = $("#input").val().split("\n");
    
    0 讨论(0)
  • 2020-12-08 11:01

    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/

    0 讨论(0)
  • 2020-12-08 11:06

    Try this

    var lines = [];
    $.each($('textarea').val().split(/\n/), function(i, line){
       if(line && line.length){
          lines.push(line);
       }
    });
    
    0 讨论(0)
提交回复
热议问题