【问题标题】:How to count Cyrillic characters in JavaScript?如何计算 JavaScript 中的西里尔字符?
【发布时间】:2019-12-01 13:31:00
【问题描述】:

我有以下代码,但它不适用于西里尔字符。

      let words = input.value.match(/\b[-?(\w+)?]+\b/gi);
      // console.log(words);
      if (words) {
        wordCount.innerHTML = words.length;
      } else {
        wordCount.innerHTML = 0;
      }

有没有办法只匹配和计算西里尔字符?

【问题讨论】:

  • 您是在尝试匹配一般字符还是仅使用西里尔文?您可以计算所有空格并将其从字符串长度中减去
  • 这不再是问题了。现在我的部分代码在西里尔文文本中找不到最重要的单词。
  • 您的具体问题是什么?我无法从您的问题中真正看出,您能否更新它并添加一些示例,以便我们准确了解您的期望?

标签: javascript regex counting cyrillic


【解决方案1】:

您现在可以在 JavaScript RegExp 模式中使用 Unicode 属性(或类别)类。

要测试字符串中是否有西里尔字符,请使用

/\p{Script_Extensions=Cyrillic}/u.test(string)
/\p{Script=Cyrl}/u.test(string)

请参阅ECMAScript documentation 表 54 中的其他 ScriptScript_extension 值。

要将所有西里尔字符匹配为字符数组,请使用

string.match(/\p{Script=Cyrl}/gu)

要获得计数,只需使用

string.match(/\p{Script=Cyrl}/gu).length

如果您需要查找西里尔字符块数,请使用

string.match(/\p{Script=Cyrl}+/gu)

查看 JavaScript 演示:

const string = 'Name: Драгослав Ивковић';
console.log(/\p{Script=Cyrl}/u.test(string));
// => true, there is at least one Cyrillic
console.log(string.match(/\p{Script=Cyrl}/gu));
// => ["Д","р","а","г","о","с","л","а","в","И","в","к","о","в","и","ћ"]
console.log(string.match(/\p{Script_Extensions=Cyrillic}+/gu));
// => Two chunks found: ["Драгослав","Ивковић"]
console.log(string.match(/\p{Script=Cyrl}/gu).length); // => 16

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    相关资源
    最近更新 更多