如何检测textarea中的前一行是否为空

时间:2016-06-15 17:51:11

标签: javascript jquery

是否可以检测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吗?

2 个答案:

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