2

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
    `","` =====> `/,/g` – Pranav C Balan Apr 04 '20 at 10:05
  • 1
    From the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace): *If pattern is a string, only the first occurrence will be replaced.* – Raul Sauco Apr 04 '20 at 10:07
  • Does this answer your question? [How to replace all occurrences of a string?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string) – Nikhil Ponduri Apr 04 '20 at 10:14

4 Answers4

3

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

user54321
  • 622
  • 6
  • 18
1

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);
}
baao
  • 71,625
  • 17
  • 143
  • 203
1

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,"");
}
Nikhil Ponduri
  • 409
  • 9
  • 28
0

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 :)

Community
  • 1
  • 1
Chandan Purbia
  • 285
  • 4
  • 14