SW프로그래밍/Util 모음

숫자 포맷 변경

고랑이. 2022. 7. 6. 10:22

전화번호에 하이픈(-) 넣기

export const formatTelNumber = (value: string): string => {
  let formatvalue = '';

  switch (value.length) {
    case 12:
      formatvalue = value.replace(/(\d{4})(\d{4})(\d{4})/, '$1-$2-$3');
      break;
    case 11:
      formatvalue = value.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3');
      break;
    case 8:
      formatvalue = value.replace(/(\d{4})(\d{4})/, '$1-$2');
      break;
    default:
      if (value.indexOf('02') === 0) {
        if (value.length === 9) formatvalue = value.replace(/(\d{2})(\d{3})(\d{4})/, '$1-$2-$3');
        if (value.length === 10) formatvalue = value.replace(/(\d{2})(\d{4})(\d{4})/, '$1-$2-$3');
      } else {
        formatvalue = value.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
      }
      break;
  }

  return formatvalue;
};

금액에 컴마(,) 넣기

export const moneyFormat = (value: string, mark?: string): string => {
  const markStr = mark ? mark : ',';
  const regExp = /\B(?=(\d{3})+(?!\d))/g;
  return value.toString().replace(regExp, markStr);
};