The regex you used (/\d|,/
) means "a digit or a comma", which means that you are replacing the numbers and commas with ''
(that is, is removing all numbers and commas from the string).
I suggest doing it in parts: first remove the letters and then remove the decimals:
let x = '3b4,4444444a';
x = x.replace(/[a-zA-Z]/g, '').replace(/(,\d{3})\d+/, '$1');
console.log(x); // 34,444
For letters I used [a-zA-Z]
(any letter of a
to z
, uppercase or lower case).
To the decimal places I used parentheses to form a capture group, and within them I put ,\d{3}
(comma followed 3 numbers). Since this part is within parentheses, if there is a comma followed by 3 numbers, they will be part of the capture group. And since it’s the first pair of parentheses, then it’ll be the first group.
Then there’s \d+
(one or more digits), and instead of substituting for the empty string, I use the reference $1
, which means "everything that corresponds to the first capture group". In our case, it is the comma followed by 3 digits. Therefore, I keep the comma and the next 3 digits, and delete all numbers from the fourth decimal place onwards.
Also note that to remove the letters I use the flag g
, for thus all letters are removed. Already in the second regex I do not use the g
, 'cause I’m assuming there’s only gonna be one comma followed by numbers.
In addition, the regex /[a-zA-Z]/g
does not consider accented letters. If you want, you can change it to /[a-záàâãéèêíïóôõöúçñ]/ig
(with the option i
to accept as many uppercase as lowercase, so it is shorter). If you want, in this question has other regex options for accented letters.