Javascript/dingbats:计算字符串中✔的个数

Javascript/dingbats: counting the number of ✔'s in a string

我正在尝试计算给定字符串中的复选标记。我的字符串可能是:

var myString = "one ✔ two ✔ three ✔"

我试过使用 myString.match(/✔/g) || []).length;,但这会返回 0(我相信会发生这种情况,因为 ✔ 是一个 dingbat 符号)。

我知道“✔”的 unicode 是 2714,我可以在我的表达式中使用它吗?

用unicode做字符串匹配没有问题。 match 方法 returns 匹配元素的数组。为了计算总数,您需要该数组中元素的总数。我相信您正在寻找的代码是:

myString.match(/✔/g).length

我已经解决了我的问题: 我将 "unicode escape sequence" \u 与 2714 unicode 一起使用:

.match(/\u2714/g) || []).length;

问题可能是由于字符编码问题(请参阅我的问题的评论),但此解决方案似乎是一个安全的选择。