javascript 文字列から数値のみを抽出する

javascript 文字列から数値のみを抽出する

javascriptで、文字列から数値のみを抽出するサンプルコードを記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 106.0.5249.103

文字列から数値のみを抽出する

文字列から数値のみを抽出するには、「正規表現」を使用します。

const str = 'a0b12c3d4';

const result = str.replace(/\D/g, '');

console.log( result ); // 01234

console.log( Number(result) ); // 1234

数値が存在しない場合は「0」が返ってしまうため、

const str = 'abcde';

const result = str.replace(/\D/g, '');

console.log( result ); // 

console.log( Number(result) ); // 0

以下のように、チェックが必要です。

const str = 'abcde';

const result = str.replace(/\D/g, '');

console.log( result ); // 

if(result !== '' ) console.log( Number(result) ); //

サンプルコード

以下は、テキストフォームに入力された文字列から数値のみを抽出して表示するサンプルコードとなります。

※cssには「bootstrap material」を使用してます。関数はアロー関数を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>

<body>
  <div id="foo" class="container text-center w-25" style="margin-top:150px">

    <h2><span id="result" class="badge badge-info">実行結果</span></h2>

    <input id="txt" type="text" class="form-control" />

    <button id="btn" type="button" class="btn btn-info btn-rounded mt-1">
      実行
    </button>

  </div>

  <script>    

    btn.onclick = () => {      

      txt.value.replace(/\D/g, '') !== '' ? result.textContent = Number(txt.value.replace(/\D/g, '')) : result.textContent = '数値が含まれてません' ;

    }
    
  </script>
</body>

</html>

抽出されていることが確認できます。