DIV CSS 佈局教程網

Node.js 的 Buffer.byteLength 詳解:計算字串的位元組長度
編輯:關於JavaScript     

處理多國語言字串時,「字元數」與「位元組數」往往並不相同。Buffer.byteLength 就是專門用來取得字串位元組長度的方法。

方法作用

它會回傳一段字串在指定編碼下所佔用的位元組數。這點與 String.prototype.length 有本質差異——後者回傳的是字元數量,而非位元組數。

基本語法

Buffer.byteLength(string, [encoding])

參數說明

  • string:要計算的字串。
  • encoding:字串編碼,預設為 'utf8'。

實作範例

str = '\u00bd + \u00bc = \u00be';
console.log(str + ": " + str.length + " characters, " +
  Buffer.byteLength(str, 'utf8') + " bytes");
// ½ + ¼ = ¾: 9 characters, 12 bytes

這個例子很直觀:同樣一段字串,字元數是 9,但在 utf8 編碼下卻佔了 12 個位元組。這正是為什麼在計算 Buffer 所需空間時,必須用 byteLength 而非 length。

原始碼解析

它會依不同編碼採用不同的計算策略,例如 hex 是長度除以二、utf16 是長度乘以二,而 utf8 等則交由底層的 internal.byteLength 精算:

Buffer.byteLength = function(str, enc) {
  var ret;
  str = str + '';
  switch (enc) {
    case 'ascii':
    case 'binary':
    case 'raw':
      ret = str.length;
      break;
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      ret = str.length * 2;
      break;
    case 'hex':
      ret = str.length >>> 1;
      break;
    default:
      ret = internal.byteLength(str, enc);
  }
  return ret;
};
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved