user2970202 user2970202 - 2 months ago 17
HTML Question

Singular VS Plural Words with Javascript?

This is the code I'm using for a Javascript countdown timer:

<script type="text/javascript">
function ShowTimes1() {
var now = new Date();
if (now.getHours() < 6) {
newVar = 5
} else if (now.getHours() < 12) {
newVar = 11
} else if (now.getHours() < 18) {
newVar = 17
} else {
newVar = 23
}
var hrs = newVar - now.getHours();
var mins = 59 - now.getMinutes();
var secs = 59 - now.getSeconds();
var str = '';
str += '<b><a href="discount.php" style="text-decoration:none;cursor:default;"><span style="color:#FF9600;">Limited Time Offer!</span> <span style="color:#489FDC;">' + hrs + ' Hours ' + mins + ' Minutes ' + secs + ' Seconds</span></a></b>';
document.getElementById('countdownToMidnight').innerHTML = str
}
var _cntDown;

function StopTimes() {
clearInterval(_cntDown)
}
</script>


It works almost perfectly, except for one thing. It always shows "hours", "minutes", and "seconds" instead of the singular version when there is only 1. For example, I want it to show "1 second" instead of "1 seconds".

This is the specific part of the code that handles displaying that text:

'+hrs+' Hours '+mins+' Minutes '+secs+' Seconds


Is there any simple way to fix my code to make this happen?

Answer

Use Ternary operator to simplify your job.

Try,

'+ hrs +' Hour' + ((hrs>1)?'s':'') +mins+' Minute' + ((mins>1)?'s':'') +secs+' Second' + ((secs>1)?'s':'')

Full line code:

str += '<b><a href="discount.php" style="text-decoration:none;cursor:default;"><span style="color:#FF9600;">Limited Time Offer!</span> <span style="color:#489FDC;">'+ hrs +' Hour' + ((hrs>1)?'s':'') +mins+' Minute' + ((mins>1)?'s':'') +secs+' Second' + ((secs>1)?'s':'')+ ' Seconds</span></a></b>';