I built a function to mask an input when typing and it works fine but when deleting the value in the input the mask behaves strangely.
function App() {
const [phone, setPhone] = React.useState('')
function maskPhone({ target: { value } }) {
console.log(value)
const toMatch = value.replace(/\D/g, '')
const regex = /(\d{0,2})(\d{0,1})(\d{0,4})(\d{0,4})/
const [,ddd, prefix, first, second] = toMatch.match(regex)
setPhone(`(${ddd}) ${prefix} ${first} ${second}`)
}
return <div>
phone: <input type='text' onChange={maskPhone} value={phone} />
</div>
}
ReactDOM.render(<App/>, document.querySelector('#root'))
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
You need to make almost all the parts of the regex optional with (?:\s*(\d{n,m}))?
kind of pattern, and then check if the group matched, and build the replacement pattern dynamically. The first part with parentheses also needs a tweak because of those parentheses.
Here is a working solution:
function App() {
const [phone, setPhone] = React.useState('')
function maskPhone({ target: { value } }) {
console.log(value)
var reg = /^(\d{1,2})(?:\s*(\d)(?:\s*(\d{1,4})(?:\s*(\d{1,4}))?)?)?$/
setPhone(value.replace(/\D/g,'').replace(reg, (_,w,x,y,z) =>
( w.length>0 ? `(${w}` : "") + ( x ? `) ${x}` : "") + ( y ? ` ${y}` : "") + ( z ? ` ${z}` : "") ))
}
return <div>
phone: <input type='text' onChange={maskPhone} value={phone} />
</div>
}
ReactDOM.render(<App/>, document.querySelector('#root'))
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>