程式碼:
<script type="text/javascript"> function utf8DisplayLength(str){ var length = 0; //單一字符的長度 var displayLength = 0; //單一字符的顯示寬度 var totalDisplayLength = 0; //全部寬度 for (var i = 0; i < str.length; i++){ var chr = str.charAt(i); if(/^[\u0000-\u007f]$/.test(chr)) { length = 1; displayLength = 1; } else if(/^[\u0080-\u07FF]$/.test(chr)) { length = 2; displayLength = 1; } else if(/^[\u0800-\uFFFF]$/.test(chr)) { length = 3; displayLength = 2; } else if(/^[\u010000-\u10FFFF]$/.test(chr)) { length = 4; displayLength = 2; } totalDisplayLength += displayLength; } return totalDisplayLength; } var str='一二三śЯ'; var result = utf8DisplayLength(str); document.write(result); </script>
結果是 8。
沒有留言:
張貼留言