SaiGiridhar SaiGiridhar - 28 days ago 8
Javascript Question

How can I use JavaScript's replace function to divide a matched number by 100?

I am trying to divide a regex-matched number in string format by 100 within JavaScript's

replace
function:

var number = "4354543";
var result = number.replace(/(\d+)/, '$1/100');
console.log(result); -> Printing 4354543/100


The answer should be
43545.43
, but instead I'm getting
"4354543/100"
.

Is it possible to achieve this?

Answer

If you know that the input strings are at least 3 digits, a simple solution is to insert a decimal separator before the last 2 digits.

var number = "4354543"; 
var result = number.replace(/(\d+)(\d{2})/, '$1.$2');
console.log(result);

However, using a function as the second argument to .replace, as the answer by James Thorpe does, gives you more flexibility.