代码之家  ›  专栏  ›  技术社区  ›  Albizia

获取包含超过0xffff的Unicode字符的字符串长度

  •  3
  • Albizia  · 技术社区  · 7 年前

    我用这个字符,双尖 '𝄪' Unicode是0x1D12A。
    如果我在字符串中使用它,我就不能得到正确的字符串长度:

    str = "F𝄪"
    str.length // returns 3, even though there are 2 characters!
    

    我如何获得返回正确答案的函数,不管我是否使用特殊Unicode_m?

    3 回复  |  直到 7 年前
        1
  •  0
  •   Adelin    7 年前

    "̉mủt̉ả̉̉̉t̉ẻd̉W̉ỏ̉r̉̉d̉̉".length == 24

    this (great) blog post

    function fancyCount(str){
      const joiner = "\u{200D}";
      const split = str.split(joiner);
      let count = 0;
        
      for(const s of split){
        //removing the variation selectors
        const num = Array.from(s.split(/[\ufe00-\ufe0f]/).join("")).length;
        count += num;
      }
        
      //assuming the joiners are used appropriately
      return count / split.length;
    }
    
    console.log(fancyCount("F𝄪") == 2) // true
        2
  •  2
  •   daxim Fayland Lam    7 年前
    String.prototype.codes = function() { return [...this].length };
    String.prototype.chars = function() {
        let GraphemeSplitter = require('grapheme-splitter');
        return (new GraphemeSplitter()).countGraphemes(this);
    }
    
    console.log("F𝄪".codes());     // 2
    console.log("👩‍❤️‍💋‍👩".codes());     // 8
    console.log("❤️".codes());      // 2
    
    console.log("F𝄪".chars());     // 2
    console.log("👩‍❤️‍💋‍👩".chars());     // 1
    console.log("❤️".chars());      // 1
    
        3
  •  0
  •   Remy Lebeau    7 年前

    F 0x0046

    𝄪 0xD834 0xDD2A

    length 计算编码的代码单元数,而不是Unicode代码点数。