我正在寻找一种方法来浏览整个网站,查找英制单位,例如磅、英尺、英寸,并将它们转换为公制值、公斤、米、厘米。
示例:
<main>
<h1>Top speed of new car is 300mph/h</h1>
<p>
Such a fast car, previously going only 250 mph, now topping speeds up to 300mph.
And it only weighs 300lbs, 20 pounds less than before!
</p>
</main>
变成:
<main>
<h1>Top speed of new car is 482.8km/h</h1>
<p>
Such a fast car, previously going only 402km/h, now topping speeds up to 482.8km/h.
And it only weighs 136kg, 9kg less than before!
</p>
</main>
问题不是如何从 mph/lbs 转换为 kmh/kg,而是如何查找和存储诸如“10mph”、“10 mph”、“200lbs”、“200 lbs”、“200 磅”之类的值“以一种好的方式,转换它们并最终替换它们。
任何指示都会非常有帮助!
编辑我想要实现的目标的简化示例:
<p>This is 10 lbs</p>
<p>This is 20lbs</p>
<script>
$('p').each(function(){
var text = $(this).text().toLowerCase();
if(text.indexOf('lbs') >= 0) {
// Store "XX lbs" in a variable
// Wrap the above created variable in a <span>
// Convert the variable to kg
// Replace the text in <span> with the value in kilogram
// Output: <p>This is <span>4.5kg</span></p>
}
});
</script>
最佳答案
那么,您可以首先构建应该从什么转换到什么的单位及其转换比率的映射:
var unitMapping = {
mph : { unit : 'km/h', ratio : 1.609 }, // there is no such thing as mph/h ?
lbs : { unit : 'kg', ratio : 0.45 },
pounds : { unit : 'kg', ratio : 0.45 }
};
现在您需要用正确的值替换文本。首先创建一个匹配所有单位的正则表达式:
var regexp = new RegExp('(\\d*) ?(' + Object.keys(unitMapping).join('|') + ')', 'g');
编写一个巧妙的替换函数,它采用非标准单位并返回标准单位:
var replaceFunction = function(match, value, unit){
return value*unitMapping[unit].ratio + unitMapping[unit].unit;
};
最后通过获取文本并将其替换为正确的版本将所有内容组合在一起:
var replaceNode = document.querySelector('main');
replaceNode.innerHTML = replaceNode.innerHTML.replace(regexp, replaceFunction);
演示:http://jsbin.com/UPEmEjuS/1/edit
如您所见,unitMapping 中有一些重复。显然,可以通过使映射依赖于标准化单位来改进解决方案,但我选择此选项是因为它使 SO 帖子的代码更清晰。
关于javascript - 查找所有英制单位并替换为相应的公制单位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21407676/