Search code examples
javascriptjqueryhtmlmasking

Mask a input in HTML using javascript


How can I mask a HTML input text with a mask for phone number?

Here in Brazil, in some states, the number format can change. For example:

(dd)xxxx-xxxx this is the default number format, where dd is the state code, and the x's are the numbers.

BUT, in some states, the number nine is added to the phone number, like this: (dd)9xxxx-xxxx. (let's call it "new format")

the var dd isn't important, what I want to do is when the user type the new format, the hyphen automatically appears after the 4th X.


Solution

  • When the users start entering the phone number, you could have a regex such as ^(\d{2})9 and regex match the string to see if the hyphen needs to be added at a different place.