How to create a regex to delete letters and number after the 3rd decimal place

Asked

Viewed 645 times

2

I need a regular expression with the following rules:

  • Erase all that is letter
  • Delete all number after 3rd decimal place

For example, if I type 34,444 any next number will be deleted. If I type a will also be erased.

 $scope.validateLimits = function(){
    $scope.numLimiteInferior = $scope.numLimiteInferior.replace(/\d|,/g,'');
 }

1 answer

3


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.