How can I manipulate a user’s phone number input, but save it unformatted on submit with React Hooks?

I am new to React and am trying to store a phone number as a 10 digit number, but look nice and formatted when the user types it in. Below is what I have so far, but I can’t quite figure out what I need to do to bring it back to a 10 digit number on submit:

    const handlePhoneChange = (event, { name, value }) => {
        const phoneRegex = /^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/g
        setInputs((inputs) => 
            Object.assign({}, inputs, {
                [name]: value.replace(phoneRegex, "($1) $2-$3")
    const handleSubmit = (event) => {
        if (event) {
     return { inputs, handlePhoneChange };

At the end of the day, I need the user’s input to look like value.replace(phoneRegex, "$1$2$3") on callback, but look like value.replace(phoneRegex, "($1) $2-$3") when the user inputs it in the UI. Hopefully, that made sense and I appreciate anyone who can help expand my knowledge here.

Source: JavaSript – Stack Overflow

August 18, 2021
Category : News
Tags: javascript | reactjs | regex | user-input

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.