【问题标题】:Substring of a Turkish String土耳其字符串的子字符串
【发布时间】:2016-10-09 20:28:30
【问题描述】:

我有一个这样的字符串

var element = "İstanbul";

当我像这样将它转换为小写时:

var element = element.toLowerCase();

变成了

"istanbul"

我需要小写字符串"istanbul"的子字符串。

所以,当我在小写操作之前这样做时

element.substr(0,2)

输出正确

但是当我执行以下操作时,我知道substr(0,2) 应该给"is" 而不是i 是错误的

为什么会这样,我该如何纠正?

【问题讨论】:

  • 你能展示一些工作代码来调试吗?
  • str.substr(0,2) 据我所知正在正常返回。可能你需要参考doc,上面写着The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.
  • 是的,根据此信息,上层工作正常,但下层没有。
  • 请添加一些代码进行调试。您正在尝试的较低的在哪里,第一个在哪里?
  • @titi23 我认为添加了所有需要的调试代码

标签: javascript string utf-8 substring


【解决方案1】:

试试

element.toLowerCase().replace(new RegExp("İ".toLowerCase(), "g"), "i");

而不是

element.toLowerCase();

【讨论】:

    【解决方案2】:

    发生这种情况是因为在更改为小写时字符串被规范化,İ 变成 2 个字符:"i"http://www.fileformat.info/info/unicode/char/0069/index.htm)和"̇"(后者是一个变音符号http://www.fileformat.info/info/unicode/char/0307/index.htm) .

    为防止出现这种情况,您可以使用 ES2015 字符串迭代工具将字符串拆分为字符,并将字符分别小写:

    const arr_l_new = [...str].map(s => s.toLowerCase());
    

    那么就可以取前N个字符了:

    const first_2_chars = arr_l_new.slice(0, 2).join('');
    

    注意:如果您计算first_2_chars 的长度,您会注意到它的长度为3,这是由于变音字符,实际上对于小写i 是不可见的。

    var str = "İstanbul";
    const arr_l = [...str].map(s => s.toLowerCase());
    const first_2_l = arr_l.slice(0, 2).join('');
    
    console.log(first_2_l, first_2_l.length);

    【讨论】:

    • 这个我没注意到。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 2014-07-25
    相关资源
    最近更新 更多