getting a string length that contains unicode character exceeding 0xffff

前端 未结 4 1595
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 06:23

I’m using this character, double sharp \'

4条回答
  •  北海茫月
    2021-01-14 07:14

    To sumarize my comments:

    That's just the lenght of that string.

    Some chars involve other chars as well, even if it looks like a single character. "̉mủt̉ả̉̉̉t̉ẻd̉W̉ỏ̉r̉̉d̉̉".length == 24

    From this (great) blog post, they have a function that will return correct length:

    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

提交回复
热议问题