javascript 文字列内で最後にある数値を取得する

javascript 文字列内で最後にある数値を取得する

javascriptで、文字列内で最後にある数値を取得するサンプルコードを記述してます。「match」で正規表現で「+$」を使用することで取得できます。最後の文字が数値でない場合は機能しないコードになってます。

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 107.0.5304.88

最後に見つかった数値を取得

文字列内で最後に見つかった数値を取得するには「match」で正規表現を使用して取得します。
※「+(プラス)」は連続した「$(ドルマーク)」は末尾という正規表現になります。

let strNum = 'AAA_01'

console.log( Number(strNum.match(/\d+$/)[0]) ) ; // 1

strNum = '11_AAA_10'

console.log( Number(strNum.match(/\d+$/)[0]) ) ; // 10

strNum = '11_AAA010'

console.log( Number(strNum.match(/\d+$/)[0]) ) ; // 10

「Number」で数値化しない場合は「0」がついた状態で文字列として取得されます。

let strNum = 'AAA_01'

console.log( (strNum.match(/\d+$/)[0]) ) ; // 1

strNum = '11_AAA_10'

console.log( (strNum.match(/\d+$/)[0]) ) ; // 10

strNum = '11_AAA010'

console.log( (strNum.match(/\d+$/)[0]) ) ; // 010

末尾の数値だけを取得したい場合は、連続を意味する「+」を外して使用します。

let strNum = 'AAA_01'

console.log( (strNum.match(/\d$/)[0]) ) ; // 1

strNum = '11_AAA_10'

console.log( (strNum.match(/\d$/)[0]) ) ; // 0

strNum = '11_AAA010'

console.log( (strNum.match(/\d$/)[0]) ) ; // 0

最後が数値でない

最後が数値でない場合は、エラーとなります。

let strNum = '111AAA'

console.log( (strNum.match(/\d+$/)[0]) ) ; 
// Uncaught TypeError: Cannot read properties of null (reading '0')

エラーを回避するため、最後の文字列が数値であることを条件にした条件式を追加して関数化してみます。

function getLastNum(str){

 // 数値であるかを判定
  if(Number.isFinite(Number(str.slice(-1)))) return Number(str.match(/\d+$/)[0]);

  return '';

}

console.log( getLastNum('AAA1') ); // 1
console.log( getLastNum('AAA12') ); // 12
console.log( getLastNum('AAA012') ); // 12
console.log( getLastNum('AAA') ); // 
console.log( getLastNum('123') ); // 123

サンプルコード

以下は、
「 実行 」ボタンをクリックすると、フォームに入力された値で最後に見つかった数値が数値であれば取得して表示するサンプルコードとなります。

※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 class="container text-center w-50" style="margin-top:200px">

    <h2><span class="badge badge-info">結果</span></h2>

    <form>
      <div class="form-group">        
        <input type="text" id="setData">
      </div>
    </form>

    <button type="button" onclick="seachFirstNum()" class="btn btn-info mt-1">
      取得
    </button>

  </div>

  <script>    

    const seachFirstNum = () => {

      let obj = document.getElementsByClassName("badge")[0];

      obj.textContent = Number(setData.value[setData.value.search(/[0-9]/)]);

    }

  </script>
</body>

</html>

取得されていることが確認できます。