Home > Software engineering >  Can we write a regex to accept all the duplicate '.' that is decimal points in a string?
Can we write a regex to accept all the duplicate '.' that is decimal points in a string?

Time:10-05

I want to accept all the decimal points, just the decimal points in the string except the first one. For example- 1.2 should be rejected but in 1..2 or 1.2.3, all the decimals after the first one should be accepted by the regex

CodePudding user response:

We can try the following regex approach using a callback function:

var input = "1..2.3.4";
var output = input.replace(/^(.*?\.)(.*)$/g, (x, y, z) => y   z.replace(/\./g, ""));
console.log(output);

The logic here is to match the first portion of the input string up to, and including, the very first dot, in the first capture group. Then, in the second capture group, we match the remainder of the string and we strip all dots from this component.

  • Related