- <html>
- <head>
- <script language="javascript">
- function alertLength() {
- var name = document.main.name.value;
- window.alert("入力文字:【" + name + "】");
- var length = countLength(name);
- window.alert("バイト数:" + length);
- }
- function countLength(str) {
- var r = 0;
- for (var i = 0; i < str.length; i++) {
- var c = str.charCodeAt(i);
- // Shift_JIS: 0x0 ~ 0x80, 0xa0 , 0xa1 ~ 0xdf , 0xfd ~ 0xff
- // Unicode : 0x0 ~ 0x80, 0xf8f0, 0xff61 ~ 0xff9f, 0xf8f1 ~ 0xf8f3
- if ((c >= 0x0 && c < 0x81) || (c == 0xf8f0) || (c >= 0xff61 && c < 0xffa0) || (c >= 0xf8f1 && c < 0xf8f4)) {
- r += 1;
- } else {
- r += 2;
- }
- }
- return r;
- }
- </script>
- </head>
- <body>
- <form name="main">
- <input type="text" name="name">
- <input type="button" onClick="alertLength()">
- </form>
- </body>
- </html>
来源: http://www.bubuko.com/infodetail-2022593.html