728x90

자바스크립트에서 숫자를 표기할때 3자리마다 콤마를 찍어줘야 할 때가 있다 자주 사용하는 기능인데 매번 만들기란 여간 귀찮은게 아니다.

콤마찍기

1
2
3
4
5
//콤마찍기
function comma(str) {
    str = String(str);
    return str.replace(/(\d)(?=(?:\d{3})+(?!\d))/g, '$1,');
}

콤마풀기

1
2
3
4
5
//콤마풀기
function uncomma(str) {
    str = String(str);
    return str.replace(/[^\d]+/g, '');
}

복사 붙여넣기로 사용하자!

input box에서 사용자 입력시 바로 콤마를 찍어주기 위한 함수도 추가 한다.

1
2
3
4
5
function inputNumberFormat(obj) {
    obj.value = comma(uncomma(obj.value));
}
 
//<input type="text" onkeyup="inputNumberFormat(this)" />

 

+ Recent posts