If number ends with 1 do something

Viewed 7770

I want to make something like this:

if(day==1 || day==11 || day==21 || day==31 || day==41 ......){
    result="dan";
}
else{
    result="dana";
}

How can i do that with every number that ends with one and of course without writing all numbers?

5 Answers

You can convert the number to a string and use String.prototype.endsWith().

const number = 151

const isMatch = number.toString().endsWith('1')

let result = ''

if (isMatch) {
    result = 'dan'
} else {
    result = 'dana'
}

I'm using it in some code that sets the ordinal. For example, if you want to display 1st, 2nd, 3rd, or 4th:

        let ordinal = 'th';
        if (number.toString().endsWith('1')) {
            ordinal = 'st'
        }
        if (number.toString().endsWith('2')) {
            ordinal = 'nd'
        }
        if (number.toString().endsWith('3')) {
            ordinal = 'rd'
        }
Related