SaiGiridhar SaiGiridhar - 1 year ago 93
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


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

The answer should be
, but instead I'm getting

Is it possible to achieve this?

Answer Source

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');

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download