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

不拆分表情符号的JavaScript子字符串

  •  1
  • user2875404  · 技术社区  · 6 年前

    在我的js里,我试图 substring() 文本通常是有效的,但不幸的是断头情感。

    usaText = "A🇺🇸Z"
    splitText = usaText.substring(0,2) //"A�"
    splitText = usaText.substring(0,3) //"A🇺"
    splitText = usaText.substring(0,4) //"A🇺�"
    splitText = usaText.substring(0,5) //"A🇺🇸"
    

    有没有一种方法可以在不破坏表情符号的情况下使用子字符串?在我的产品代码中,我把它删去了大约40个字符,我不介意它是35个还是45个。我曾想过简单地检查第40个字符是数字还是介于a-z之间,但如果你的文本中充满了表情符号,那就行不通了。我可以检查最后一个字符是否是一个通过模式匹配“结束”表情符号的字符,但这在性能方面似乎也有点奇怪。

    我错过什么了吗?JavaScript承载了大量的数据,但是没有内置的 count 将表情符号视为一体?

    Split JavaScript string into array of codepoints? (taking into account "surrogate pairs" but not "grapheme clusters")

    chrs = Array.from( usaText )
    (4) ["A", "🇺", "🇸", "Z"]
    0: "A"
    1: "🇺"
    2: "🇸"
    3: "Z"
    length: 4
    

    1 回复  |  直到 6 年前
        1
  •  10
  •   MichaelSolati    6 年前

    所以这真的不是一件容易的事,我倾向于告诉你,你不应该自己写这个。你应该使用像这样的图书馆 runes .

    只是一个简单的 npm i runes ,然后:

    const runes = require('runes');
    const usaText = "A🇺🇸Z";
    runes.substr(usaText, 0, 2); // "A🇺🇸"
    
        2
  •  2
  •   E. Villiger    5 年前

    免责声明:这只是扩展了Mike'Pomax'Kamermans的上述评论,因为对我来说,这实际上是一个更简单、适用的答案(对于我们这些不喜欢通读所有评论的人):

    数组.from(str) 将字符串拆分为单个unicode字符,而不在字节之间打断它们。

    看到了吗 Split JavaScript string into array of codepoints? (taking into account "surrogate pairs" but not "grapheme clusters") 详情。

        3
  •  1
  •   hs_dino    5 年前

    splitText = Array.from(usaText).slice(0, 5).join('');