首页 > 解决方案 > 我可以使用正则表达式来计算一年的世纪吗?

问题描述

创建一个接收一年并返回正确世纪的函数。所有年份都在 1000 到 2010 年之间。11 世纪在 1001 到 1100 年之间。18 世纪在 1701 到 1800 年之间。

有没有办法使用正则表达式来做到这一点?我知道这很长,但我只是想适应正则表达式。

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"

标签: javascriptregex

解决方案


不需要正则表达式,甚至不需要冗长的比较字符串。一些简单的算术将完成这项工作:

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

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

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

// e.g. 18th century

我意识到,当我们进入 21 世纪时,这会以较小的方式失败。你可以解决这个问题!


推荐阅读