簡體   English   中英

將字符串截斷為 1 MB 大小限制

[英]truncate the string to 1 MB size limit

我需要切割字符串 - 基本上,如果字符串超過 1 MB,我應該將其切割成這個大小。

我正在使用這些函數來檢查字符串大小

function __to_mb(bytes) {
   return bytes / Math.pow(1024, 2)
}

function __size_mb(str) {
  return __to_mb(Buffer.byteLength(str, 'utf8'))
}

然后我像這樣檢查字符串的大小

if (__size_mb(str) > 1) { /* do something */ }

但是怎么剪呢?

一個 Javascript 字符串由 16 位序列組成,一些字符使用一個 16 位序列,其他字符需要兩個 16 位序列

沒有簡單的方法可以只取一定數量的字節並認為它已完成 - 在截止位置的兩側可能有一個2x 16 位字符,然后將其切成兩半。

為了安全起見,我們可以使用str.codePointAt(index)中引入的str.codePointAt(index) 它知道哪些字符是 16 位的,哪些是2x 16 位的。 它將這些 16 位值中的 1 個或 2 個組合成一個整數結果值。

  • 如果codePointAt()返回一個值 <= 2^16-1那么我們在偏移index處有一個 16 位字符。
  • 如果codePointAt()返回一個 >= 2^16的值,那么我們在偏移量indexindex+1處有一個2x 16 位字符。

不幸的是,這意味着遍歷整個字符串來評估每個索引。 這可能看起來很尷尬,甚至可能很慢,但我不知道這樣做的更快或更聰明的方法。

演示:

 var str = "abç🔥😂déΩf👍g😏h"; // string of 13 characters console.log("str.length = " + str.length); // shows 17 because of double-width chars console.log("size in bytes = " + str.length * 2); // length * 2 gives size in bytes var maxByteLengths = [8, 16, 24, 32, 40]; for (var maxBytes of maxByteLengths) { var data = safeCutOff(str, maxBytes); console.log(maxBytes + " bytes -> " + data.text + " (" + data.bytes + " bytes)"); } function safeCutOff(str, maxBytes) { let widthInBytes = 0; for (var index = 0; index < str.length; /* index is incremented below */ ) { let positionsUsed = str.codePointAt(index) <= 0xFFFF ? 1 : 2; newWidthInBytes = widthInBytes + 2 * positionsUsed; if (newWidthInBytes > maxBytes) break; index += positionsUsed; widthInBytes = newWidthInBytes; } return { text: str.substring(0, index), bytes: widthInBytes }; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM