javascript Unicodeコードポイントから文字列を作成する
- 2021.02.17
- javascript
- javascript

javascriptで、fromCodePointを使用して、Unicodeコードポイントから文字列を作成するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
fromCodePoint使い方
fromCodePointを使用すると、Unicodeコードポイントから文字列を作成することが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 |
console.log( String.fromCodePoint(97) // a ); console.log( String.fromCodePoint(97,98) // ab ); // サロゲートペアもOK console.log( String.fromCodePoint(128514) // 😂 ); |
文字列を配列化して、引数に一括で指定することも可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// 文字列を用意。サロゲートペア文字も対処 const str = 'ab😂😃😉'.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[\s\S]/g) || []; // 配列を用意 let arr = []; // 配列にUnicodeコードポイントを1文字ずつ挿入 for (var i = 0; i < str.length; ++i) { arr.push(str[i].codePointAt(0)); } // 可変長の引数として配列を引数に指定 console.log(String.fromCodePoint(...arr)); // ab😂😃😉 |
上記のfor文は、以下のようにforEachを使用することも可能です。
1 |
[...Array(str.length)].forEach((x, i) => arr.push(str[i].codePointAt(0))); |
サンプルコード
以下は、
「実行」ボタンをクリックすると、フォームに入力されたUnicodeコードポイントを文字列に変換して表示する
サンプルコードとなります。
※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。関数はアロー関数を使用してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 30px; } </style> <script> const hoge = () => { // 文字列に変換して表示 result.innerHTML = String.fromCodePoint(foo.value) } window.onload = () => { // クリックイベントを登録 btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略 } </script> <body> <div class="main container"> <h2><span id="result" class="badge bg-info">変換</span></h2> <div class="mb-3"> <input id="foo" type="text" class="form-control"> </div> <div class="row"> <button id="btn" type="button" class="btn btn-warning"> 実行 </button> </div> </div> </body> </html> |
文字列に変換されて表示されていることが確認できます。

-
前の記事
centos7でASP.NET Coreを実行するまで 2021.02.16
-
次の記事
React.js ライブラリ「supercons」を使って フレンドリーで親しみやすいアイコンを使用する 2021.02.17
コメントを書く