Skip to content

Instantly share code, notes, and snippets.

@jikeytang
Created June 19, 2014 01:55
Show Gist options
  • Save jikeytang/3f5e9c0118c27178bc8c to your computer and use it in GitHub Desktop.
Save jikeytang/3f5e9c0118c27178bc8c to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140619-题目1
求一个字符串的字节长度;
//假设一个中文占两个字节
/*var str = 'hello中国';
PS:
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。
```javascript
// you code
```
2. 粘贴代码时请使用shift+tab,缩进前面的空白。
@ljkfgh2008
Copy link

new function(s) 
{ 
    if(!arguments.length||!s) return null; 
    if(""==s) return 0; 
    var l=0; 
    for(var i=0;i<s.length;i++) 
    { 
        if(s.charCodeAt(i)>255) l+=2; 
        else l++; 
    } 
    console.log(l); 
}("hello中国");

@hjzheng
Copy link

hjzheng commented Jun 19, 2014

上面的答案不是很准确,在没有确定中文编码范围情况下,笼统的认为编码大于255就是汉字啦。而且不同编码汉字范围是不同的。

@mailzwj
Copy link

mailzwj commented Jun 19, 2014

function getByteLen(str) {
    var len = str.length,
        doubLen = str.match(/\W/g).length;
    return (len - doubLen) + doubLen * 2;
}
getByteLen('Hello中国');

@zjhsd2007
Copy link

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