How to remove thousand separaters in number using javascript?

Viewed 60

problem:

I want to remove the comma in a string and make it as a number.

It means,

  • 234,345 should become 234345.
  • 1,234 should become 1234
  • 4,567,890 should become 4567890

I have created one code like this.

let a = "5,245"
function numberWithoutCommas(x) {
    return x.replace(",","");
}
const b = parseInt(numberWithoutCommas(a))
console.log(typeof(b))
console.log(b)

This is failing when there more comma in the string.It means 1,234,567 gives 1234. So can someone help me to achieve it?

4 Answers

Splitting and joining should do the job
return x.split(',').join('');

You can simply parse to a number and use a regex

const s = ['5,332', '39,322,322,233']
function numberWithoutCommas(x) {
    return Number(x.replace(/,/g, ''));
}
for (const a of s) {
    const n = numberWithoutCommas(a);
    console.log(n, typeof n);
}

passing string as a first argument to replace method will only replace the very first occurrence.

let str = '111,11,11,1';
str.replace(',','') // result:- 11111,11,1

use regex instead

str.replace(/,/g,'') //result:- 11111111

in your use case

function numberWithoutCommas(x) {
    return x.replace(/,/g,"");
}

The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

Note: If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier.

So, to replace all the occurrences of ,, we should rather use /,/g instead of just ,.

Then your code would be something like the following

let a = "1,234,567"
function numberWithoutCommas(x) {
    return x.replace(/,/g,"");
}
const b = parseInt(numberWithoutCommas(a))
console.log(typeof(b))
console.log(b)

I hope this helps :)

Related