I have a problem to convert input in HTML to specific criteria :
- Maximum 4 digit with dot (ex : 5.100)
- Only accept number
- Separate with dot if thousand
I am able to achieve the last two with this :
value.replace(/\D/g, "").replace(/\B(?=(\d{3}) (?!\d))/g, ".");
How to add the first criteria ?
And seems like my regex is too long, a shorter one would be great.
CodePudding user response:
Remove all but first four digits:
const value = `123456`
console.log(
value.replace(/\D/g, "").replace(/^(\d{4})\d /, '$1').replace(/\B(?=(\d{3}) (?!\d))/g, ".")
)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I would use a mask for the input,
("#id").inputmask({
mask: "9.999",
placeholder: "",
separator: "",
});
Then to check the value,
value.replace('.','');
and with a regular expression to verify that it is true that they are only digits and at most 4.
let regex_aux = /^\d{4}/;
if(regex_aux.test(value)){
//do something
}