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.
source to share
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);
}
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.
source to share