あのぞんブログ

絵文字を含めて文字数カウントするWebアプリ作った

2020-10-02

アプリ

emoji-count

絵文字対応

"text".split('') では絵文字が 1 文字として分割できません。

> "😔"
'😔'
> "😔".split('')
[ '�', '�' ]

punycode.js を使います。

const punySplit = (s: string) =>
  punycode.ucs2.decode(s).map((v) => punycode.ucs2.encode([v]))

punySplit('😔')
// [ '😔' ]
punySplit('😔😎')
// [ '😔', '😎' ]

カウントする関数

エスケープ文字の可視化

そのまま React で render すると改行文字(\n)が見えないのでバックスラッシュをエスケープしました。

function visibleEscapeChars(text: string) {
  return text
    .replace(/\t/g, '\\t')
    .replace(/\v/g, '\\v')
    .replace(/\n/g, '\\n')
    .replace(/\r/g, '\\r')
    .replace(/\f/g, '\\f')
    .replace(/\0/g, '\\0')
}

なにかこういうライブラリあれば知りたいです。


© 2025 あのぞんびより All Rights Reserved