javascript - 使用 JavaScript 将 5'5" 表示法中的英尺转换为厘米
问题描述
我有很多高度,以英寸为单位,如果它们在其他高度之间,则需要检查它们。但是,数据并非 100% 完美。有时数字显示为5'5"
有时5' 5"
(带有空格)。它之间出现的高度也会有所不同,有时看起来像5'5" - 5'10"
,有时像5' 5"-5' 10"
,有时像5'5"-5' 10" Height
......你明白了。
因此,我正在尝试构建一个函数,该函数将采用类似的数字并5'5"
确认该数字在 format 的高度范围之间。true
false
5' 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\"")
解决方案
这使用了一个类似的正则表达式,但删除了^
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
推荐阅读
- python - python opencv检测具有表面缺陷的产品图像之间的差异
- javascript - 使用 js codeigniter 以表单形式读取文件
- javascript - 是否可以在 React Web 应用程序中实现地理围栏功能
- java - 仅从 jdbc 中的表中获取第一行
- python - 如何使用 SQL 在 python 中的两个日期之间进行搜索
- html - CSS:覆盖父元素样式
- java - 关闭会话后立即触发 destroyListener
- php - 使用 CURL 和 PHP 向由线程分隔的同一 URL 发送多个请求
- php - 碳 - 日期采用 ISO8601 格式,带有偏移表示法
- apache-spark - 分区中的火花模式差异