Question

A plain text file made up of paragraphs and some blank lines is loaded into an array via Ajax. The array is split into elements by new lines, such as:

var infoArray = new Array();
infoArray = response.split("\n");

Then the array is put through a for loop, with various tests for keywords in various elements, which indicate the next n-elements get processed in particular ways. Mostly the elements are output, such as

    strMsg += '<li>' + infoArray[i] + '</li>';

The Problem is blank lines from the text file are also saved into array elements. Then a blank list item gets output and is noticeably wrong.

Need a test condition just to check if the array element is empty or contains a newline character, I'm not sure which applies. Plus the server is buggy and sometimes takes a minute to load new info so I'm sometimes not sure if I am refreshing my most recent code or not.

Some of the things I've tried:

    if (!(infoArray[i].substring(0,0) == '')) { /* process output */ }
    if (!(infoArray[i].substring(0,1) == '\n')) { /* process output */ }
    if (!(infoArray[i].substring(0,0) == '\n')) { /* process output */ }
    if (!(infoArray[i].substring(0,1) == /\n/)) { /* process output */ }
    if (!(infoArray[i].substring(0,1) == /\n/)) { /* process output */ }
    if (!(infoArray[i].substring(0,1) == /\n|\s*\n/)) { /* process output */ }
    if (!(infoArray[i].IsEmpty())) { /* process output */ }

    var tempString = infoArray[i].toString();
    if (!(tempString.IsEmpty())) { /* process output */ }
    if (tempString.length != 0) { /* process output */ }

Ideas?

Edit: oh yeah I also tried doing an 'encode' and 'decode' before checking for '\n' just to bring it out.

No correct solution

OTHER TIPS

Try trimming the string with a RegEx. I think this one is popular (taken from first google hit):

if (!(infoArray[i].replace(/^\s+|\s+$/g, '') == ''))

WebKit publishes another set of trim functions you could use.

I would suggest to just trim array element. For example, you can use jQuery:

if (infoArray[i] = $.trim(infoArray[i])) {
    strMsg += '<li>' + infoArray[i] + '</li>';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top