javascript 文字のUnicodeコードポイントを取得する

javascript 文字のUnicodeコードポイントを取得する

javascriptで、codePointAtを使用して、文字のUnicodeコードポイントを取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.134

codePointAt使い方

codePointAtを使用すると、Unicodeコードポイントを取得することが可能です。

const str = 'abあいう';

for (let i = 0; i < str.length; ++i) {
	console.log(str.codePointAt(i));
}

実行結果

ちなみに、上記は、for文を1行で記述することもできます。

const str = 'abあいう';

[...Array(str.length)].forEach((x, i) => console.log(str.codePointAt(i)));

サンプルコード

以下は、
「実行」ボタンをクリックすると、フォームに入力された文字列のUnicodeコードポイントを表示する
サンプルコードとなります。

※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。

<!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>

  function hoge() {

    // フォームに入力された文字列
    const str = txt.value; // document.getElementById('txt');を省略

    // Unicodeコードポイントを表示
    disp(str, "result");

  }

  //フロントに表示する関数
  function disp(str, id) {
    
    let text = [];
    // forEachを使用
    [...Array(str.length)].forEach((x, i) => text.push('<li class="list-group-item">' + str.codePointAt(i) + '</li>'));

    //innerHTMLを使用して表示    
    document.getElementById(id).innerHTML = text.join('');
  }

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
  }

</script>

<body>
  <div class="main container">

    <h2><span class="badge bg-info">Unicodeコードポイント</span></h2>
    <ul id="result" class="list-group list-group-flush"></ul>
    <div class="mb-3">
      <input id="txt" type="text" class="form-control">
    </div>

    <div class="row">
      <button id="btn" type="button" class="btn btn-warning">
        実行
      </button>
    </div>

  </div>

</body>

</html>

Unicodeコードポイントが表示されていることが確認できます。