Javascript extracting number from string

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

They look like this:

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

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

(So, I go with β‰ˆ

 var productPriceDiff = DKK 100"; 

or simply:

var productPriceDiff = 100"; )

Can someone help me do this?

Thanks Jakob

+4
source share
4 answers

First you need to convert input prices from strings to numbers. Then subtract. And you will have to convert the result back to the format "DKK ###, ##". These two functions should help.

 var priceAsFloat = function (price) { return parseFloat(price.replace(/\./g, '').replace(/,/g,'.').replace(/[^\d\.]/g,'')); } 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)); 
+10
source

to try:

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

edit: this will get the price, including numbers, commas and periods. it does not validate the format of a number or number, periods, etc. are adjacent. If you can be more accurate in determining the exact numbers you use, this will help.

+5
source

try also:

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

This should make productCurrentPrice the actual number you follow after (if I understood your question correctly).

+1
source

Source: https://habr.com/ru/post/1286144/


All Articles