<div class="box">
  <div>
    
  <h2>첫번째 코드 <span>- ^(\d{2,3})(\d{3,4})(\d{4})$</span></h2>
  <input type="text" oninput="autoHyphen(this)" maxlength="13" placeholder="전화번호를 입력해보세요!" autofocus>
  </div>
  <div>
    
    <h2>두번째 코드 <span>- ^(\d{0,3})(\d{0,4})(\d{0,4})$</span></h2>
  <input type="text" oninput="autoHyphen2(this)" maxlength="13" placeholder="전화번호를 입력해보세요!">
  </div>
</div>
input {
  width: 20rem;
  height: 3rem;
  border-radius: 5px;
  padding-left: 1rem;
  border: 1px solid #e0e5f6;
  background: #fff;
}

h2 {
  font-size: 1.2rem;
  margin: .6rem 0;
}

h2 span {
  font-size: 1rem;
  font-weight: 500;
  color: #555;
}

.box > div {
  margin: 3rem 1rem;
}

/* ---- */

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  outline: none;
  word-break: break-all;
  font-family: Pretendard;
}

body {
  background: #f7f8fc;
}
const autoHyphen = (target) => {
 target.value = target.value
   .replace(/[^0-9]/g, '')
   .replace(/^(\d{2,3})(\d{3,4})(\d{4})$/, `$1-$2-$3`);
}

const autoHyphen2 = (target) => {
 target.value = target.value
   .replace(/[^0-9]/g, '')
  .replace(/^(\d{0,3})(\d{0,4})(\d{0,4})$/g, "$1-$2-$3").replace(/(\-{1,2})$/g, "");
}

External CSS

  1. https://cdn.jsdelivr.net/gh/orioncactus/pretendard/dist/web/static/pretendard.css

External JavaScript

This Pen doesn't use any external JavaScript resources.