【问题标题】:Can `toLowerCase` change a JavaScript string's length?`toLowerCase` 可以改变 JavaScript 字符串的长度吗?
【发布时间】:2021-11-02 16:54:25
【问题描述】:

有没有可能string.length !== string.toLowerCase().length

鉴于Change to .length with toUpperCase? 的答案,我知道toUpperCase 是可能的,但我不知道toLowerCase 是否可能。

【问题讨论】:

  • 我的意思是,根据您的链接,如果某些字符根据其大小由不同数量的字符定义,那么yes。在这种情况下,可以应用相同的方法并表明 .toLowerCase() 会给出长度 1 而不是最初定义的 2(大写状态)。
  • @DragonInTraining 不一定是这样。在toUpperCase 之后调用toLowerCase 时,链接问题的答案中给出的示例不会导致字符串恢复到其原始长度。自己看吧。

标签: javascript string unicode internationalization string-length


【解决方案1】:

是的,这是可能的,并非所有的大小写映射都是一对一的,它们也可以是一对多的,正如您在从小写到大写时看到的那样,从大写到小写时也是如此。这可以通过 LATIN CAPITAL LETTER I WITH DOT ABOVE 字符 (0x0130) 看到:

const char = "\u0130"; // İ
const charLower = char.toLowerCase();
console.log(char, char.length); // İ 1
console.log(charLower, charLower.length); // i̇ 2
console.log(char.length !== charLower.length); // true

规范中有一条注释也在22.1.3.26 部分强调了这种行为:

某些码点的大小写映射可能会产生多个码点。 在这种情况下,结果字符串的长度可能与 源字符串

可以在Unicode Character Database (UCD) 中找到特殊情况映射的列表(即:不一定一对一的情况映射)。如所列,某些字符的长度仅在某些条件下才会增加,其中一些取决于特定的上下文和语言环境:

// From the UCD for SpecialCasings, another example can be found: 
// 012E; 012F 0307; 012E; 012E; lt More_Above; # LATIN CAPITAL LETTER I WITH OGONEK
// The above means '012E' maps to the lower case of '012F 0307' if:
// - the locale is Lithuanian (lt)
// - the suffix contains a character of combining class 230 (Above)
// \u0300 is a character with such a combining class value (list found here: https://www.compart.com/en/unicode/combining/230)

const grapheme = '\u012E\u0300'; // Į̀ (Į +  ̀ )
console.log(grapheme, grapheme.length); // Į̀ 2

const lowerStd = grapheme.toLowerCase();
console.log(lowerStd, lowerStd.length); // į̀ 2 (still fine)

const lowerLocale = grapheme.toLocaleLowerCase('lt');
console.log(lowerLocale, lowerLocale.length); // į̇̀ 3 (now 3 when using lt as the locale)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 2014-06-21
    • 1970-01-01
    • 2012-02-24
    相关资源
    最近更新 更多