2006/10/17

如何計算JavaScript字元的長度

當內容有中文時,字體的寬度會佔顯示的二個位元。

String.prototype.getLength = function() {
// 先找出佔二位元的字體(例如:中文)
var zh = this.match(/[^\x00-\xff]/ig);
// this.length + match到的字元個數(意思就是中文字會算二次)
return this.length + (zh == null ? 0 : zh.length);
}

使用的方式:

function test(){
var src = "1234五";
alert(src.getLength());
}

結果會出現 : 6

No comments: