jQuery textarea 글자 수 세기 (공백포함, 공백제외)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
</head>
<body>
<div class="checker_spell">
<textarea name="content" id="character_counter_content" cols="70" rows="22" class="checker_input"
placeholder="내용을 입력해주세요."></textarea>
</div>
<div class="summary">
<p><span>공백 포함</span><strong class="letter" id="current_msglen">00</strong><span>자</span><strong class="byte"
id="current_msg_byte">00</strong><span>byte</span></p>
<p><span>공백 제외</span><strong class="letter" id="current_msglen_except_blank">00</strong><span>자</span><strong
class="byte" id="current_msg_byte_except_blank">0</strong><span>byte</span></p>
</div>
<div class="wrap_btns">
<button type="button" class="btn_basic2 type03 btn_copy" id="copy_all">전체 복사</button>
</div>
<script>
(function (window, $, undefined) {
var $character_counter_content = $('#character_counter_content'),
$st_len = $('#current_msglen'),
$st_byte = $('#current_msg_byte'),
$steb_len = $('#current_msglen_except_blank'),
$steb_byte = $('#current_msg_byte_except_blank');
//복사 하기
$("#copy_all").on('click', function () {
copyAll();
});
//실시간 글자수 세기
$character_counter_content.keyup(function () {
chkMsgLength(this);
});
function copyAll() {
if ($character_counter_content.val() === '') {
alert('내용을 입력 해주세요.');
return;
}
$character_counter_content.select();
document.execCommand('copy');
alert("입력하신 내용이 복사되었습니다.\n\nCtrl + v 키를 사용하여, 붙여 넣기를 사용하실 수 있습니다.");
setTimeout(function () {
try {
if (document.selection) {
document.selection.empty();
} else {
window.getSelection().removeAllRanges();
}
} catch (e) { }
}, 1);
}
//텍스트 길이 계산
function chkMsgLength(objMsg) {
//공백 포함
var vacuum_pattern = /\r\n/gm;
var vacuum_text;
var vacuum_length;
//공백 미포함
var vacuum_remove_pattern = /\s/gm;
var vacuum_remove_text;
var vacuum_remove_length;
vacuum_text = $(objMsg).val();
vacuum_length = lengthMsg($(objMsg).val());
vacuum_remove_length = lengthMsg(vacuum_text.replace(vacuum_remove_pattern, ''));
vacuum_text = vacuum_text.replace(vacuum_pattern, '\n');
vacuum_remove_text = vacuum_text.replace(vacuum_remove_pattern, '');
$st_len.html(vacuum_text.length);//현재 글자수를 넣는다
$st_byte.html(vacuum_length);//현재 byte수를 넣는다
$steb_len.html(vacuum_remove_text.length);//현재 글자수를 넣는다
$steb_byte.html(vacuum_remove_length);//현재 byte수를 넣는다
}
//텍스트 바이트단위 계산
function lengthMsg(obj_msg) {
var nbytes = 0;
var i;
for (i = 0; i < obj_msg.length; i++) {
var ch = obj_msg.charAt(i);
if (encodeURIComponent(ch).length > 4) { // 한글일경우
nbytes += 2;
} else if (ch === '\n') { // 줄바꿈일경우
if (obj_msg.charAt(i - 1) !== '\r') { // 하지만 밀려서 줄이 바뀐경우가 아닐때
nbytes += 1;
}
} else { //나머지는 모두 1byte
nbytes += 1;
}
}//END FOR
return nbytes;
}
})(window, jQuery, undefined);
</script>
</body>
</html>
참고 사이트
www.saramin.co.kr/zf_user/tools/character-counter