views:

1228

answers:

4

Hi,

I have a bunch of strings extracted from html using jQuery.

They look like this:

var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";

I need to extract the number values in order to calculate the price difference.

(So I wend up with ≈

var productPriceDiff = DKK 100";

or just:

var productPriceDiff = 100";)

Can anyone help me do this?

Thanks, Jakob

+2  A: 

try:

var productCurrentPrice = productBeforePrice.replace(/[^\d.,]+/,'');

edit: this will get the price including numbers, commas, and periods. it does not verify that the number format is correct or that the numbers, periods, etc are contiguous. If you can be more precise in the exact number definitions you expcet, it would help.

Jonathan Fingland
Pretty sure that you need to escape that period, actually.
inkedmn
pretty sure you don't. it's inside the []. outside of that and it would need escaping. just tested in firefox and it's working as expected
Jonathan Fingland
+1  A: 

try also:

var productCurrentPrice = productBeforePrice.match(/\d+(,\d+)?/)[0];
Keeper
A: 
var productCurrentPrice = parseInt(productBeforePrice.replace(/[^\d\.]+/,''));

That should make productCurrentPrice the actual number you're after (if I understand your question correctly).

inkedmn
fails on commas as provided in his example of number format for danish kroners.
Jonathan Fingland
+4  A: 

First you need to convert the input prices to floats. Then subtract. And you'll have to convert the result back to "DKK ###,##" format. These two functions should help.

var priceAsFloat = function (price) {  
   return parseFloat(price.replace(/\./g, '').replace(/,/g,'.').replace(/[^\d\.]/g,''), 10);
}

var formatPrice = function (price) {  
   return 'DKK ' + price.toString().replace(/\./g,',');
}

Then you can do this:

var productBeforePrice = "DKK 399,95"; 
var productCurrentPrice = "DKK 299,95";
productPriceDiff = formatPrice(priceAsFloat(productBeforePrice) - priceAsFloat(productCurrentPrice));
Patrick McElhaney
Works perfectly! (-: Thank you so much.
Just realized it doesn't work with larger prices like "DKK 1.299,95".
Okay, I fixed it to work with larger prices by stripping all of the periods before doing anything else.I didn't fix the formatPrice function. It will return a valid price, but without the periods ("DKK 1299,95"). If you need help doing that, ask another question. :-)
Patrick McElhaney