javascript 正規表示を利用して指定した文字の数をカウントする手順
- 2020.08.08
- javascript
- javascript

javascript で、正規表示を利用して文字列から指定した文字数をカウントするサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
※windows10にApacheのインストールはこちら
文字の数カウント
正規表現を使用して、文字列「 mebee mebee 」から文字「e」の数をカウントするプログラムです。
※cssには「uikit」を使用してます。
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 57 58 59 60 61 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <!-- UIkit CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3.5.5/dist/css/uikit.min.css" /> <!-- UIkit JS --> <script src="https://cdn.jsdelivr.net/npm/uikit@3.5.5/dist/js/uikit.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/uikit@3.5.5/dist/js/uikit-icons.min.js"></script> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 20px; } </style> <script> window.onload = function(){ //文字列を取得 var msg = document.getElementById('txt1').textContent; //countを初期化 var count = 0; // 正規表現を利用 var ex = /e/g; var arr = msg.match(ex); //指定した文字のカウント count = arr.length; //フロントに結果を表示 txt2.textContent = "配列 : " + arr; txt3.textContent = "カウントした文字数 : " + count; } </script> <body> <div class="main"> <div class="uk-alert-primary" uk-alert> <p id="txt1">mebee mebee</p> </div> <div class="uk-alert-success" uk-alert> <p id="txt2"></p> </div> <div class="uk-alert-success" uk-alert> <p id="txt3"></p> </div> </div> </body> </html> |
実行結果を確認すると、使用されている「e」の数が正しくカウントされていることがわかります。

-
前の記事
php ライブラリ「filp/whoops」を使ってエラー画面を見やすくに表示する 2020.08.08
-
次の記事
Nuxt.js ライブラリ「vue-slider-component」をインストールしてスライダーを実装する 2020.08.08
コメントを書く