Javascript从字符串中提取数字

4 javascript string jquery numbers extract

我有一堆使用jQuery从html中提取的字符串.

它们看起来像这样:

var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";
Run Code Online (Sandbox Code Playgroud)

我需要提取数值以计算价格差异.

(所以我≈we

var productPriceDiff = DKK 100";
Run Code Online (Sandbox Code Playgroud)

要不就:

var productPriceDiff = 100";)

任何人都可以帮我这样做吗?

谢谢你,雅各布

Pat*_*ney 10

首先,您需要将输入价格从字符串转换为数字.然后减去.而且你必须将结果转换回"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,',');
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

var productBeforePrice = "DKK 399,95"; 
var productCurrentPrice = "DKK 299,95";
productPriceDiff = formatPrice(priceAsFloat(productBeforePrice) - priceAsFloat(productCurrentPrice));
Run Code Online (Sandbox Code Playgroud)


Jon*_*and 5

尝试:

var productCurrentPrice = productBeforePrice.replace(/[^\d.,]+/,'');
Run Code Online (Sandbox Code Playgroud)

编辑:这将获得包括数字,逗号和句点在内的价格.它不验证数字格式是否正确或数字,句号等是否连续.如果您可以更精确地确定您所描述的确切数字定义,那将会有所帮助.