-3

Create a function that takes in a year and returns the correct century. All years will be between 1000 and 2010. The 11th century is between 1001 and 1100. The 18th century is between 1701-1800.

Is there a way to do this using regexes? I understand that it's long but I'm just trying to get comfortable with regexes.

function century(num) {
      
      if (/1000/ig.test(num) === true) {
        return '10th century';
      } else if (/[1001-1100]/ig.test(num) === true) {
      return '11th century';
      } else if (/[1101-1200]/ig.test(num) === true) {
      return '12th century';
      } else if (/[1201-1300]/ig.test(num) === true) {
      return '13th century';
      } else if (/[1301-1400]/ig.test(num) === true) {
      return '14th century';
      } else if (/[1401-1500]/ig.test(num) === true) {
      return '15th century';
      } else if (/[1501-1600]/ig.test(num) === true) {
      return '16th century';
      } else if (/[1601-1700]/ig.test(num) === true) {
      return '17th century';
      } else if (/[1701-1800]/ig.test(num) === true) {
      return '18th century';
      } else if (/[1801-1900]/ig.test(num) === true) {
      return '19th century';
      } else if (/[1901-2000]/ig.test(num) === true) {
      return '20th century';
      } else if (/[2001-2100]/ig.test(num) === true) {
      return '21th century';
      } else {
        return undefined;
      }
    }
    console.log(century(1756)); //"18th century"
    console.log(century(1555)); //"16th century"
    console.log(century(1000)); //"10th century"
    console.log(century(1001)); //"11th century"
    console.log(century(2005)); //"21th century"
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Ron Janko
  • 7
  • 1
  • Regex is completely wrong for this. No part of the problem description suggests a regular expression is necessary. If you want to use a big series of comparisons, you just need a simple `<`. – user229044 Mar 15 '21 at 02:05
  • This is just simple math, `return Math.ceil(num/100)` – Nick Mar 15 '21 at 02:09

1 Answers1

-2

No need for regular expressions, or even lengthy strings of comparisons. Some simple arithmetic will do the job:

let year = window.prompt("What year?");

let century = Math.floor((year-1)/100)+1

console.log(century+'th century');

// e.g. 18th century

I realise that this fails in minor way when we reach the 21st century. You can sort that out!