首页 > 解决方案 > 使用 JavaScript 将 5'5" 表示法中的英尺转换为厘米

问题描述

我有很多高度,以英寸为单位,如果它们在其他高度之间,则需要检查它们。但是,数据并非 100% 完美。有时数字显示为5'5"有时5' 5"(带有空格)。它之间出现的高度也会有所不同,有时看起来像5'5" - 5'10",有时像5' 5"-5' 10",有时像5'5"-5' 10" Height......你明白了。

因此,我正在尝试构建一个函数,该函数将采用类似的数字并5'5"确认该数字在 format 的高度范围之间。truefalse5' 5"-5' 10"

function checkHeight(userHeight) {

  var rex = /^(\d+)'(\d+)(?:''|")$/;
  var match = rex.exec(userHeight);
  var feet, inch;

  if (match) {
    feet = parseInt(match[1], 10);
    inch = parseInt(match[2], 10);
    console.log("feet = " + feet + ", inches = " + inch);
  } else {
    console.log("Didn't match");
  }

};

checkHeight("5' 5\"")

标签: javascriptfunctionrange

解决方案


这使用了一个类似的正则表达式,但删除了^and$因此匹配可以在任何地方发生并添加 a\s*以便在英尺和英寸之间可以有任意数量的空白。它还以更简单的方式进行测试,并避免cm完全转换为:

function checkHeight( userHeightStr, heightRangeStr ) {
    const [ userHeight, minHeight, maxHeight ] =
      [ userHeightStr, ...heightRangeStr.split('-') ].map( heightStr => { 
        const [ , feet, inches ] = heightStr.match( /(\d+)'\s*(\d+)(?:''|")/ );
        return feet*12 + +inches;
      } )
    ;
    console.log( 'Heights in inches: ', { userHeight, minHeight, maxHeight } );
    return minHeight <= userHeight && userHeight <= maxHeight;
}

console.log( checkHeight("5' 4\"","5'  5\" - 6' 1\" Height") ); // false
console.log( checkHeight("5' 5\"","5'5\" - 6' 1\" Height") ); // true
console.log( checkHeight("5'10\"","5'5\"-5' 10\"") ); // true
console.log( checkHeight("5'11\"","5'5\"   -5' 10''") ); // false


推荐阅读