jQuery / 천 단위 쉼표 만드는 방법
예제 1
텍스트로 출력된 숫자에 천 단위 쉼표를 넣는다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <script src="//code.jquery.com/jquery-3.3.1.min.js"></script> <script> $( document ).ready( function() { $( '#jb' ).text( $( '#jb' ).text().replace( /\,/g, '' ).replace( /(\d)(?=(?:\d{3})+(?!\d))/g, '$1,' ) ); } ); </script> <style> body { font-family: Consolas; font-size: 40px; } </style> </head> <body> <p id="jb">123456789</p> </body> </html>
예제 2
폼에 입력하면 실시간으로 쉼표가 붙는다. 주의할 점은 쉼표도 포함하여 전송한다.
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <script src="//code.jquery.com/jquery-3.3.1.min.js"></script> <script> $( document ).ready( function() { $( '.jb' ).on( 'keyup', function() { $( this ).val( $( this ).val().replace( /\,/g, '' ).replace( /(\d)(?=(?:\d{3})+(?!\d))/g, '$1,' ) ); } ); } ); </script> <style> body { font-family: Consolas; font-size: 40px; } input { font-family: inherit; font-size: inherit; } </style> </head> <body> <input type="text" name="price" class="jb"> </body> </html>