Remove empty lines from a string in Javascript

Here is a small function to remove empty lines from a string without the need for regular expressions.

function delBlankLines(myString) {

    var stringArray = myString.split('\n');
    var temp = [""];
    var x = 0;

    for (var i = 0; i < stringArray.length; i++) {
        if (stringArray[i].trim() != "") {
            temp[x] = stringArray[i];
            x++;
        }
    }

    temp = temp.join('\n');
    return temp;
}

Leave a Comment

Your email address will not be published. Required fields are marked *