rob.m rob.m - 1 year ago 73
jQuery Question

How to output objects with conditional?

I am running the following:

if (doSelect('Location').length > 0 && doSelect('Date').length > 0 || doSelect('State').length > 0 && doSelect('Date').length > 0) {
var dateText = doSelect("Date").siblings('td').text().split(/\s+/g);
console.log(dateText);
$wikiDOM.find('.nourlexpansion').remove();
$wikiDOM.find("#coordinates").parent().remove();
$('#results').append('<li>' + curTitle + "<br>" + doSelect("Location").siblings('td').text() + '<br>' +
dateText[0] + "&nbsp; " + dateText[1].replace(/,/g , '&nbsp; ') + "&nbsp; " + dateText[2].replace(/;/g , '&nbsp; ') + "&nbsp;" + dateText[3].replace(/,/g , '&nbsp; ') + "&nbsp; " + dateText[4] + "&nbsp; " + dateText[5] + "&nbsp; " + '</li>');
}


This line defines possible results:

var dateText = doSelect("Date").siblings('td').text().split(/\s+/g);


The console could give:

["19", "May", "1945", "–", "22", "August", "1945"]


So to print these dates I do:

dateText[0] + "&nbsp; " + dateText[1].replace(/,/g , '&nbsp; ') + "&nbsp; " + dateText[2].replace(/;/g , '&nbsp; ') + "&nbsp;" + dateText[3].replace(/,/g , '&nbsp; ') + "&nbsp; " + dateText[4] + "&nbsp; " + dateText[5] + "&nbsp;


Which gives:

19 May 1945 – 22 August

but sometimes I don't have all these dates so
dateText[3]
might not exists just as much as it may exists
dateText[9]


Not simply that, I use
.replace(/,/g , '&nbsp; ')
or
.replace(/,/g , '&nbsp; ')
because sometimes the dates come out to be all stack together like
19,May,1945
and I also need to remove the
dash
or
comma
or
semicolumn


Basically I am trying to do it in a way that it is consistent and doesn't gives error in console if certain
[N]
or
.replace
isn't needed and are not present.

This is what I am trying to achieve:


19 May 1945

22 August 1945


Sometime I even go the month and the date opposite like
August, 22, 1945
.

Am not sure how to approach this.

Answer Source

What if you try something like this?

var dateText = ["19", "May", "1945", "–", "22", "August", "1945"];

var d = '';

for(var i = 0; i < dateText.length; i++) {
    d += dateText[i] + ' ';
}

console.log(d);

Console output: 19 May 1945 – 22 August 1945

To get rid of the '-' and/or insert a line break you could easily modify the loop to handle that. This keeps your code clean/simple and allows for easy changes which will impact all objects of this type in the future.

Fiddle: https://jsfiddle.net/n2s7nwju/1/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download