dan.john.daly
dan.john.daly

Reputation: 96

Check for empty string is failing in js

After splitting a set of glossary terms with:

lines = text.split(/[\r\n]+/);

I then iterate through the array and parse out each term to properly format them during output. However, a simple check for empty strings has become much more of a headache than I could've ever imagined. Console logging gives me this:

...
"Pushing" "dyspnea: Labored or difficult respiration." //correct
"Pushing" ""
...

Things I have tried in order to find these empty strings:

line === ""
line.length == 0
if(line)
isNaN(line.charCodeAt(0))
typeof line == "undefined"

And various combinations of the list above. On recommendation from a coworker, I checked the line endings of the input text, but it all seemed normal.

I'm sure I'm just doing something really stupid, but the solution has eluded me for far too long. Any help/suggestions would be greatly appreciated!

Edit: Thanks for the suggestions everyone. Alas, the problem persists...

Also, I forgot to mention, but I have tried both trimming and replacing whitespace in each line after the split, but came up with nothing.

As requested, here is more relevant code.

var text = "";
var end = /\x2E\s\x5B/gm; // ". ["
var lines = [];
var terms = [];

text = document.getElementById("terms").value;
lines = text.split(/[\r\n]+/);
parseText();

function parseText() {
    var i = 0;
    while(i < lines.length) {
        var line = lines[i];
        endIndex = lines[i].search(end);

        if(line != "" || line != " " || line.length != 0 ) {
            parseTerm(lines[i].substring(0, endIndex+1));
        }

        i++;
}

Upvotes: 0

Views: 1270

Answers (3)

dan.john.daly
dan.john.daly

Reputation: 96

Turns out that in my input there was a line with two spaces. I have NO idea why this was causing problems, considering the split was specifically on the pattern described above, but replacing instances of too much whitespace fixed the issue. The new line:

text.replace(/\s\s+/g, " ").split(/[\r\n]+/);

Upvotes: 0

BinDrinkin
BinDrinkin

Reputation: 21

As the previous answer stated issue is probably whitespace, you can use the trim function to shorten your code:

if (line.trim() == "") {
    alert("Blank");
}

Upvotes: 2

kpblc
kpblc

Reputation: 902

maybe string is not a "", but " "?

so check not only zero length, but "white space"

if(st1 == "" || st1 == " " || st1.length == 0 ){
    console.log("find empty")    
}

Upvotes: 0

Related Questions