How do I use RegEx to ignore the first period and match all subsequent periods?

How do I use RegEx to ignore the first period and match all subsequent periods?

For example:

  • 1.23 (no match)
  • 1.23.45 (corresponds to the second period)
  • 1.23.45.56 (corresponds to the second and third periods)

I am trying to prevent users from entering invalid numbers. Therefore, I will use this RegEx to replace matches with empty strings.

I currently have /[^.0-9]+/

, but this is not enough to disallow .

after the (optional) initial.

+3


source to share


2 answers


I suggest using a regex that will match 1+ digits, a period, and then any number of digits and periods, fixing those 2 parts into separate groups. Then, inside the replace callback method, remove all periods with an extra replace

:

var ss = ['1.23', '1.23.45', '1.23.45.56'];
var rx  = /^(\d+\.)([\d.]*)$/;
for (var s of ss) {
  var res = s.replace(rx, function($0,$1,$2) { 
     return $1+$2.replace(/\./g, ''); 
  });
  console.log(s, "=>", res);
}
      

Run codeHide result




Template details :

  • ^

    - beginning of line
  • (\d+\.)

    - Group 1 corresponds to 1 + numbers and letters .

  • ([\d.]*)

    - zero or more characters other than numbers and literal period
  • $

    - end of line.
+1


source


Limit the number between the start ^

and end anchor $

, then specify the desired pattern. For example:

/^\d+\.?\d+?$/



Which allows 1 or more numbers, followed by an optional period, followed by optional numbers.

+2


source







All Articles