是否可以检测textarea中单行的结构。例如,这是我的textarea及其内容
this is the first line in textarea
1234 this is the second line starting with 1234
this is the fourth line and the third line is empty
所以我想检测line 3
之类的空行,并检测像line 2
这样的行的前4个字符。这可以用jQuery或JavaScript吗?
答案 0 :(得分:1)
textarea中的值只是一个字符串,您可以在换行符处拆分以获取每一行。
var arrayOfLines = $('textarea').val().split('\n');
var finalString = "";
var prevBoolean = false;
for (var i = 0; i < arrayOfLines.length; i++) {
var line = arrayOfLines[i];
if (line.length === 0) {
console.log("empty line");
} else {
// if the first 4 characters of the line are "1234" set prevBoolean to true
if (line.substring(0, 4) == "1234"){
finalString += line + "\n";
prevBoolean = true;
} else {
// add custom line, if the previous non-empty line started with "1234" and set prevBoolean back to false
if (prevBoolean == true) {
prevBoolean = false;
finalString += "custom line" + "\n";
} else {
finalString += line + "\n";
}
}
}
}
// set the value of the textarea to the finalString
$('textarea').val(finalString);
答案 1 :(得分:1)
使用$.each()
的更简单,更简洁的解决方案,因为我们可以遍历对象,并检查空行和/或以1234
开头的行:
const arr = $('textarea').val().split('\n');
$.each(arr, (k, v) => {
if (v.length === 0) console.log(k + ' is empty');
if (v.substring(0, 4) == 1234) console.log('1234 found in key: ' + k);
});