w3resource

JavaScript: Get English ordinal suffix for the day of the month

JavaScript Datetime: Exercise-23 with Solution

Write a JavaScript function to get the English ordinal suffix for the day of the month, 2 characters (st, nd, rd, or th).

Test Data :
dt= new Date();
console.log(english_ordinal_suffix(dt));
"23rd"
dt = new Date(2015, 10, 1);
console.log(english_ordinal_suffix(dt));
"1st"

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript function to get English ordinal suffix for the day of the month, 2 characters (st, nd, rd or th.)</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function english_ordinal_suffix(dt)
  {
    return dt.getDate()+(dt.getDate() % 10 == 1 && dt.getDate() != 11 ? 'st' : (dt.getDate() % 10 == 2 && dt.getDate() != 12 ? 'nd' : (dt.getDate() % 10 == 3 && dt.getDate() != 13 ? 'rd' : 'th'))); 
  }

dt = new Date();
console.log(english_ordinal_suffix(dt));

dt = new Date(2015, 10, 1);
console.log(english_ordinal_suffix(dt));

Sample Output:

20th
1st

Flowchart:

Flowchart: JavaScript- Get English ordinal suffix for the day of the month

Live Demo:

See the Pen JavaScript - Get English ordinal suffix for the day of the month-date-ex-23 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to get a full textual representation of the day of the week (Sunday through Saturday).
Next: Write a JavaScript function to get ISO-8601 week number of year, weeks starting on Monday.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

Returns 1 if the array is sorted in ascending order, -1 if it is sorted in descending order or 0 if it is not sorted

Example:

const tips_Sorted = arr => {
  let direction = -(arr[0] - arr[1]);
  for (let [i, val] of arr.entries()) {
    direction = !direction ? -(arr[i - 1] - arr[i]) : direction;
    if (i === arr.length - 1) return !direction ? 0 : direction / Math.abs(direction);
    else if ((val - arr[i + 1]) * direction > 0) return 0;
  }
};
console.log(tips_Sorted([0, 1, 2, 2]));
console.log(tips_Sorted([5, 7, 3]));
console.log(tips_Sorted([8, 6, 4])); 

Output:

1
0
-1

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook