LoginSignup
2

More than 3 years have passed since last update.

posted at

updated at

Organization

<input>要素の maxlength を絵文字にも対応させる

サロゲートペア文字列に対する対応が、最近の JS では意外と簡単にできるようになっていたので覚え書きです。:sunglasses:
ちなみに IE :poop: は非対応なので、IE 対応が必要な方は本気を出してください。

[追記] タイトルが微妙に嘘をついてました。maxlength は使わずに、最大入力文字数の制御をします。

サロゲートペア文字列を正しくカウントする

:no_good_tone1: NO GOOD

'𥹖𥹢𥹥'.length // 6
'𥹖𥹢𥹥'.split('').length // 6

:ok_woman_tone1: OK

[...'𥹖𥹢𥹥'].length // 3
Array.of(...'𥹖𥹢𥹥').length // 3
'𥹖𥹢𥹥'.match(/./ug).length // 3

参考までに、以下は<input> 要素にサロゲートペア文字列を入力すると、maxlength が正しく動作しない問題を、このやり方を使い改善したサンプルです。Vue でコンポーネント化しています。

See the Pen TextInput by Eiji Meguro (@megurock) on CodePen.

サロゲートペア文字列の文字コードを正しく取得する

String.prototype.charCodeAt() の代わりに、String.prototype.codePointAt() を使います。

:no_good_tone1: NO GOOD

'𥹖'.charCodeAt(0) // 55383

:ok_woman_tone1: OK

'𥹖'.codePointAt(0) // 155222

サロゲートペア文字列を文字コードから正しく表示する

String.fromCharCode() の代わりに、String.fromCodePoint() を使います。

:no_good_tone1: NO GOOD

String.fromCharCode(155222) // "幖"

:ok_woman_tone1: OK

String.fromCodePoint(155222) // "𥹖"

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
2