The King is The King is - 5 months ago 18
jQuery Question

How to detect if previous line in a textarea is empty

Is it possible to detect the structure of a single line in a textarea. For example this is my textarea and it's contents

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


So I want to detect empty lines like
line 3
and also detect the first 4 characters of a line like
line 2
. Is this possible with jQuery or JavaScript?

Answer

The value in textarea is simply a string, which you can split at newlines to get each line.

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