How to read line by line of a text area HTML tag

后端 未结 5 1037
借酒劲吻你
借酒劲吻你 2020-11-29 21:10

I have a text area where each line contains Integer value like follows

      1234
      4321
     123445

I want to check if the user has re

相关标签:
5条回答
  • 2020-11-29 21:52

    This works without needing jQuery:

    var textArea = document.getElementById("my-text-area");
    var arrayOfLines = textArea.value.split("\n"); // arrayOfLines is array where every element is string of one line
    
    0 讨论(0)
  • 2020-11-29 21:58

    Try this.

    var lines = $('textarea').val().split('\n');
    for(var i = 0;i < lines.length;i++){
        //code here using lines[i] which will give you each line
    }
    
    0 讨论(0)
  • 2020-11-29 22:02

    A simple regex should be efficent to check your textarea:

    /\s*\d+\s*\n/g.test(text) ? "OK" : "KO"
    
    0 讨论(0)
  • 2020-11-29 22:10

    Two options: no JQuery required, or JQuery version

    No JQuery (or anything else required)

    var textArea = document.getElementById('myTextAreaId');
    var lines = textArea.value.split('\n');    // lines is an array of strings
    
    // Loop through all lines
    for (var j = 0; j < lines.length; j++) {
      console.log('Line ' + j + ' is ' + lines[j])
    }
    

    JQuery version

    var lines = $('#myTextAreaId').val().split('\n');   // lines is an array of strings
    
    // Loop through all lines
    for (var j = 0; j < lines.length; j++) {
      console.log('Line ' + j + ' is ' + lines[j])
    }
    

    Side note, if you prefer forEach a sample loop is

    lines.forEach(function(line) {
      console.log('Line is ' + line)
    })
    
    0 讨论(0)
  • 2020-11-29 22:11

    This would give you all valid numeric values in lines. You can change the loop to validate, strip out invalid characters, etc - whichever you want.

    var lines = [];
    $('#my_textarea_selector').val().split("\n").each(function ()
    {
        if (parseInt($(this) != 'NaN')
            lines[] = parseInt($(this));
    }
    
    0 讨论(0)
提交回复
热议问题