Skip to content
Advertisement

How to make a number mask using only JavaScript?

good evening. I wanna create a mask for my JavaScript project, using only Pure JavaScript, without any jQuery stuff or anything like that. What a want to do is, while I’m writing a bunch of numbers, they will be placed in certain spots. Like, for the final format, I want to do “XXX.XXX.XXX-XX”, but, while writing, “XXX.” and then “XXX.XXX.”, like that. Right now, my code is:

JavaScript
JavaScript

So, how can I make sure that, while I am writing the numbers, the dots will appear after the 3rd, 6th, and the hyphen after the 9th number? Thanks for the help!

Advertisement

Answer

w matches any single letter, number or underscore (same as [a-zA-Z0-9_]). You can customize and add only numbers and alphabets using /[a-zA-Z0-9]/g in match function.

Intentionally I’ve used the condition e.key !== "Backspace" && e.key !== "Delete" to not add the characters in input if user use delete or Backspace key.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement