Insert hyphens in JavaScript

Viewed 47410

What is the easiest way to insert hyphens in JavaScript?

I have a phone number eg. 1234567890

While displaying in the front-end, I have to display it as 123-456-7890 using JavaScript.

What is the simplest way to achieve this?

10 Answers

If you want to mask your input in that way then you can do something like below so that when input is being given by the user it automatically formats it to the required format.

function transform(){
 let ele = document.getElementById("phno");
 ele.value = ele.value.replace(/^(\d{3})$/g, '$1-')
      .replace(/^(\d{3}\-\d{3})$/g, '$1-');
}
<input
  type="text"
  onkeyup="transform()"
  id="phno"
  placeholder="123-123-4444"
  maxlength="12"
/>

For react just use a ref like this example:

Here I just replace the value of the element and include hyphens onBlur

Logic part:

    const ref = React.useRef(null)

    const blurHandle = () => {
        ref.current.value = ref.current.value.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3")
    };

declarative render part:

<Input
  ref={phoneInput}
  onFocus={focusHandler}
  onBlur={blurHandle}
  type="tel"
  placeholder="###-###-####"
  name="from_phoneNumber"
  pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
/>

If your Input is a sepparated styled component using an input JSX element inside remember pass the ref to the children element using a foward ref

const Input = React.forwardRef((props, ref) => (
    <input type="tel" ref={ref} ........ />
))
Related