0

I want to replace a floating number by another one in my string using Javascript.

Examples:

var string1 = '$10.50';
var string2 = '$10.50 USD';
var string3 = '10.50 €';

Results:

var newFloatNb = 15.99;

string1 = '$15.99';
string2 = '$15.99 USD';
string3 = '15.99 €';

Anyway to do this? I want to keep the currencies that are not always the same.

Rubyx
  • 708
  • 1
  • 11
  • 32

1 Answers1

0

I did it, sorry for this question.

var string = '$10.50 USD';
var newFloatNb = 15.99;
var stringNumber = parseFloat(string.match(/-?(?:\d+(?:\.\d*)?|\.\d+)/)[0]).toFixed(2);
string = string.replace(stringNumber, '15.99');

console.log(string);
Rubyx
  • 708
  • 1
  • 11
  • 32
  • 1
    Note: if there are no numbers in your string, `string.match` will return undefined and your code will break (trying to access `[0]` of `undefined`). If this is a possibility, make sure to store your match in a separate variable and check the result before using it. – Bali Balo Jun 24 '19 at 18:08