ltsai ltsai -4 years ago 56
Javascript Question

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

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

For example:


  • 1.23 (no match)

  • 1.23.45 (matches the second period)

  • 1.23.45.56 (matches the second and third periods)



I am trying to limit users from entering invalid numbers. So I will be using this RegEx to replace matches with empty strings.

I currently have
/[^.0-9]+/
but it is not enough to disallow
.
after an (optional) initial
.

Answer Source

I suggest using a regex that will match 1+ digits, a period, and then any number of digits and periods capturing these 2 parts into separate groups. Then, inside a replace callback method, remove all periods with an additional 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);
}

Pattern details:

  • ^ - start of string
  • (\d+\.) - Group 1 matching 1+ digits and a literal .
  • ([\d.]*) - zero or more chars other than digits and a literal dot
  • $ - end of string.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download