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

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

      1234
4321
123445

我想检查用户是否真的输入了有效值,而不是像下面这样的有趣值

      1234,
987l;

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

203925 次浏览

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
}

A simple regex should be efficent to check your textarea:

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

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

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

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

A simplifyied Function could be like this:

function fetch (el_id, dest_id){
var dest = document.getElementById(dest_id),
texta = document.getElementById(el_id),
val = texta.value.replace(/\n\r/g,"<br />").replace(/\n/g,"<br />");
dest.innerHTML = val;
}

for the html code below (as an example only):

<textarea  id="targetted_textarea" rows="6" cols="60">
At https://www.a2z-eco-sys.com you will get more than what you need for your website, with less cost:
1) Advanced CMS (built on top of Wagtail-cms).
2) Multi-site management made easy.
3) Collectionized Media and file assets.
4) ...etc, to know more, visit: https://www.a2z-eco-sys.com
</textarea>
<button onclick="fetch('targetted_textarea','destination')" id="convert">Convert</button>


<div id="destination">Had not been fetched yet click convert to fetch ..!</div>