Created
June 19, 2014 01:55
-
-
Save jikeytang/3f5e9c0118c27178bc8c to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140619-题目1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
求一个字符串的字节长度; | |
//假设一个中文占两个字节 | |
/*var str = 'hello中国'; | |
PS: | |
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。 | |
```javascript | |
// you code | |
``` | |
2. 粘贴代码时请使用shift+tab,缩进前面的空白。 |
ljkfgh2008
commented
Jun 19, 2014
上面的答案不是很准确,在没有确定中文编码范围情况下,笼统的认为编码大于255就是汉字啦。而且不同编码汉字范围是不同的。
function getByteLen(str) {
var len = str.length,
doubLen = str.match(/\W/g).length;
return (len - doubLen) + doubLen * 2;
}
getByteLen('Hello中国');
var str = 'Hello中国',n = str.match(/[\u4e00-\u9fa5]/g)
return str.length + (n ? n.length : 0);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment