Skip to content

Instantly share code, notes, and snippets.

@tingwei628
Last active August 29, 2015 14:21
Show Gist options
  • Save tingwei628/9417c21c4f87c0e3e955 to your computer and use it in GitHub Desktop.
Save tingwei628/9417c21c4f87c0e3e955 to your computer and use it in GitHub Desktop.
[JavaScript] Blength()&subBytes()(算中英文字數)
/*
Blength() 是用來計算string 以Byte為單位
subBtyes(str, max)是用來切割Btyes(str:被切割字串, max:最大Bytes數)
例: "我abc我".Blength() = 7
subBtyes("我abc我", 3) // 結果是 我a
*/
String.prototype.Blength = function(){
var str = this.match(/[^\x00-\xff]/ig);
return str === null ? this.length : this.length + str.length;
};
var subBtyes = function(str,max){
for(var i=0; i<str.length;i++){
var SubBtyeSum=str.substring(0,i).Blength();
if(SubBtyeSum>= max){
break;
}
}
return str.substring(0,i);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment