汉字和数字混合时,按照长度进行字符截取。
<script> /** * JS实现中英文混合文字溢出友好截取功能 * @param text 字符串 * @param length 截取长度 */ var zfc = {}; zfc.mixTextOverflow = function (text, length) { if (text.replace(/[\u4e00-\u9fa5]/g, 'aa').length <= length) { return text } else { var _length = 0 var outputText = '' for (var i = 0; i < text.length; i++) { if (/[\u4e00-\u9fa5]/.test(text[i])) { _length += 2 } else { _length += 1 } if (_length > length) { break } else { outputText += text[i] } } return outputText + '...' } } console.log(zfc.mixTextOverflow('留学NEW SAT essay 题目分析和汇总', 12)) </script>
标签:中英文,text,截取,JS,length,zfc From: https://www.cnblogs.com/fnym/p/17527883.html