如何用JavaScript统计textarea字符(部分字符计为2个)
短信字符统计(特殊字符计2长度)实现方案
核心思路
短信平台的字符计数遵循GSM 03.38标准,部分特殊字符(如é、è、€、ñ等)会占用2个字符长度。实现逻辑分为三步:
- 定义符合标准的双长度特殊字符集合
- 遍历输入内容,对每个字符判断是否属于该集合,累加对应长度
- 绑定输入框的
input事件,实时更新计数
原生JavaScript实现
// 定义GSM标准中占2字符的特殊字符正则 const doubleCharsRegex = /[€éèùìòÇñѧ¿¡äöüÄÖÜßáàâãåçéêëíìîïñóòôõöúùûüýÿ]/g; // 计算实际短信字符长度的函数 function calculateSmsLength(text) { const normalCount = text.length; // 匹配到的特殊字符数量,无匹配则返回空数组处理为0 const doubleCount = (text.match(doubleCharsRegex) || []).length; // 总长度 = 普通字符数 + 特殊字符数(每个特殊字符多算1个长度) return normalCount + doubleCount; } // 绑定textarea实时统计事件 const textarea = document.getElementById('sms-input'); const countDisplay = document.getElementById('char-count'); textarea.addEventListener('input', function() { const currentLength = calculateSmsLength(this.value); countDisplay.textContent = `当前长度:${currentLength}/160`; // 超过上限时高亮提示 countDisplay.style.color = currentLength > 160 ? 'red' : 'black'; });
jQuery实现
// 定义双长度特殊字符正则 const doubleCharsRegex = /[€éèùìòÇñѧ¿¡äöüÄÖÜßáàâãåçéêëíìîïñóòôõöúùûüýÿ]/g; // 计算短信长度的工具函数 function calculateSmsLength(text) { const normalCount = text.length; const doubleCount = (text.match(doubleCharsRegex) || []).length; return normalCount + doubleCount; } // 页面加载完成后绑定输入事件 $(document).ready(function() { $('#sms-input').on('input', function() { const currentLength = calculateSmsLength($(this).val()); $('#char-count') .text(`当前长度:${currentLength}/160`) .css('color', currentLength > 160 ? 'red' : 'black'); }); });
补充说明
- 可根据业务需求扩展
doubleCharsRegex中的字符,覆盖所有需要双计数的特殊字符 input事件能覆盖键盘输入、粘贴、剪切等所有内容变更场景- 超过160字符的样式提示可根据UI设计自由调整
内容的提问来源于stack exchange,提问作者Cypoun
相关产品推荐
相关产品推荐

