我有一堆使用 jQuery 从 html 中提取的字符串。
它们看起来像这样:
var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";
我需要提取数值以计算价格差异。
(所以我找到了≈
var productPriceDiff = DKK 100";
要不就:
var productPriceDiff = 100";
)
谁能帮我做到这一点?
谢谢,雅各布
我有一堆使用 jQuery 从 html 中提取的字符串。
它们看起来像这样:
var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";
我需要提取数值以计算价格差异。
(所以我找到了≈
var productPriceDiff = DKK 100";
要不就:
var productPriceDiff = 100";
)
谁能帮我做到这一点?
谢谢,雅各布
首先,您需要将输入价格从字符串转换为数字。然后减去。您必须将结果转换回“DKK ###,##”格式。这两个功能应该有所帮助。
var priceAsFloat = function (price) {
return parseFloat(price.replace(/\./g, '').replace(/,/g,'.').replace(/[^\d\.]/g,''));
}
var formatPrice = function (price) {
return 'DKK ' + price.toString().replace(/\./g,',');
}
然后你可以这样做:
var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";
productPriceDiff = formatPrice(priceAsFloat(productBeforePrice) - priceAsFloat(productCurrentPrice));
尝试:
var productCurrentPrice = productBeforePrice.replace(/[^\d.,]+/,'');
编辑:这将获得包括数字、逗号和句点在内的价格。它不验证数字格式是否正确或数字、句点等是否连续。如果您可以在您期望的确切数字定义中更加精确,那将有所帮助。
也试试:
var productCurrentPrice = productBeforePrice.match(/\d+(,\d+)?/)[0];
var productCurrentPrice = parseInt(productBeforePrice.replace(/[^\d\.]+/,''));
这应该使 productCurrentPrice 成为您所追求的实际数字(如果我正确理解您的问题)。