SoFunction
Updated on 2025-02-28

Example of JavaScript method to calculate the actual length of string

Calculate the actual length of the string

Double-byte character (including Chinese characters) length meter 2, ASCII character meter 1

Method 1: Use match

export function getByteLenMatch(data) {
  let result = 0;
  for (let s of data) {
    result += (/[^\\x00-\\xff]/ig) == null ? 1 : 2;
  }
  return result;
}

Method 2: Use replace

export function getByteLenReplace(data) {
  return (/[^\\x00-\\xff]/ig, "aa").length;
}

Test code:

let testData = new Array(50000000).fill("ha").toString();
    for (let i = 0; i < 3; i++) {
      ("getByteLenMatch");
      getByteLenMatch(testData);
      ("getByteLenMatch");
      ("getByteLenReplace");
      getByteLenReplace(testData);
      ("getByteLenReplace");
    }

Performance comparison (units ms)

String length match replace
50,000,000 8051 8626
50,000,000 9351 8019
50,000,000 10384 7512
10,000,000 1631 1783
10,000,000 1646 1343
10,000,000 1663 1372
5,000,000 799 728
5,000,000 822 806
5,000,000 884 645
1,000,000 165 128
1,000,000 166 143
1,000,000 170 113
500,000 84 58
500,000 83 54
500,000 86 61
100,000 20 7
100,000 18 5
100,000 20 5
50,000 11.79 3.01
50,000 10.39 2.68
50,000 11.99 2.82
10,000 4.13 0.60
10,000 4.32 0.59
10,000 5.48 0.58
5,000 1.88 0.31
5,000 1.36 0.33
5,000 2.71 0.31
1,000 1.67 0.07
1,000 0.21 0.07
1,000 1.02 0.06
500 0.0840 0.0322
500 0.0820 0.0332
500 0.0840 0.0320
100 0.0229 0.0100
100 0.0432 0.0149
100 0.0471 0.0161

In the case of large data volume, the performance of replace will be inferior to match at the first time, and will be superior to match after multiple executions. In the case of small data volume, the performance of replace will be superior to match at the first time, and in the case of small data volume, the performance of replace will be superior to match at the first time, and in the case of small data volume, the performance of replace will be superior to match at the first time, and after the first time, the performance of replace will be superior to match at the first time, and after the first time, the performance of replace will be superior to match at the first time.

The above is the detailed content of the JavaScript method to calculate the actual length of a string. For more information about JavaScript calculating the length of a string, please pay attention to my other related articles!