Skip to content

Instantly share code, notes, and snippets.

@ryantbd
Last active August 29, 2015 13:57
Show Gist options
  • Save ryantbd/9613521 to your computer and use it in GitHub Desktop.
Save ryantbd/9613521 to your computer and use it in GitHub Desktop.
Javascript substr() optimized for Chinese Characters.
String.prototype.strLen = function() {
var len = 0,
offset;
for (var i = 0, tmp = this.length; i < tmp; i++) {
offset = (this.isCHS(i)) ? 2 : 1;
len += offset;
}
return len;
};
String.prototype.strToChars = function(){
var chars = [];
for (var i = 0, tmp = this.length; i < tmp; i++){
chars[i] = [this.substr(i, 1), this.isCHS(i)];
}
String.prototype.charsArray = chars;
return chars;
};
String.prototype.isCHS = function(i){
return (this.charCodeAt(i) > 255 || this.charCodeAt(i) < 0);
};
String.prototype.subCHString = function(start, end){
var len = 0,
str = '',
offset;
this.strToChars();
for (var i = 0, tmp = this.length; i < tmp; i++) {
offset = (this.charsArray[i][1]) ? 2 : 1;
len += offset;
if (end < len) {
return str;
} else if (start < len) {
str += this.charsArray[i][0];
}
}
return str;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment