如何逐行读取文本区域HTML标记

问题描述 投票:70回答:5

我有一个文本区域,其中每行包含如下的整数值

      1234
      4321
     123445

我想检查用户是否真的没有使用有效值而不是一些有趣的值,如下所示

      1234,
      987l;

为此,我需要逐行阅读文本区域并验证。如何使用javascript逐行读取文本区域?

javascript jquery html textarea
5个回答
150
投票

试试这个。

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
}

31
投票

这不需要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

5
投票

这将为您提供lines中的所有有效数值。您可以更改循环以验证,删除无效字符等 - 无论您想要哪个。

var lines = [];
$('#my_textarea_selector').val().split("\n").each(function ()
{
    if (parseInt($(this) != 'NaN')
        lines[] = parseInt($(this));
}

4
投票

一个简单的正则表达式应该有效地检查你的textarea:

/\s*\d+\s*\n/g.test(text) ? "OK" : "KO"

2
投票

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

旁注,如果您更喜欢每个样本循环

lines.forEach(function(line) {
  console.log('Line is ' + line)
})
© www.soinside.com 2019 - 2024. All rights reserved.