How do I allow only one decimal point between numbers when creating a string in the form of a number and a decimal point in regex?

I made a regular expression that accepts only numbers and decimal points in string form. Decimal points can only be placed between numbers. If a value that does not match the regular expression comes in, the value filtered through replace is put in the answer constant. For example, if "123." is entered, the answer constant will contain "123" because the decimal point is after the number, not between the digits. However, if "123.." or "123…" is entered, "123." is entered in the answer constant. I want to put "123" (The constraint is that only one decimal point can appear between numbers.)

how can i fix my regex??

this is my code

const value = "123..."

let regex = /^\.|\.$|(?<=\..*)\.|[^\d.]/g;

const answer = value.replace(regex, "")

console.log(answer);

// (expected answer :  123 but it comes 123.) 

>Solution :

It sounds like you want to remove all the ‘.’ instances at the end of the string, if they are not followed by a digit. You could try something like this:

const regex = /\.+$/;

However, that’s not perfect:

console.log('123...'.replace(regex, ''));       // 123
console.log('123...pants'.replace(regex, ''));  // 123...pants

Instead, you may be better using the regex to tell you which part of the input is actually valid, then just keeping that part; something like this:

const regex = /\d+(\.\d{1,2})?/;
const [match] = regex.exec('123.45.67...');
console.log(match);                             // 123.45

Leave a Reply