javascript アルファベットの母音の数を取得する
- 作成日 2022.10.07
- 更新日 2022.10.14
- javascript
- javascript
![javascript アルファベットの母音の数を取得する](https://mebee.info/wp-content/uploads/2022/05/javascript-4.gif)
javascriptで、アルファベットの母音の数を取得するサンプルコードを記述してます。
環境
- OS windows11 pro 64bit
- ブラウザ chrome 106.0.5249.103
母音を取得
母音のみを取得するには、正規表現を使用します。
const str = "hello world";
let result;
result = str.match(/[aeiou]/gi)
if(result !== null ) console.log( result.length ) // 3
大文字も含む場合は、正規表現に大文字を追加するか、
const str = "hEllo world";
let result;
result = str.match(/[aeiouAEIOU]/gi)
if(result !== null ) console.log( result.length ) // 3
全て小文字に変換して、結果を取得します。
const str = "hEllo world";
let result;
result = str.toLowerCase().match(/[aeiou]/gi)
if(result !== null ) console.log( result.length ) // 3
また、以下のように正規表現を使用せずに、「配列」と「for」文を使用することも可能です。
const arr = ["a", "e", "i", "o", "u"]
let str = "hello world";
let count = 0;
for (let i of str.toLowerCase()) {
if (arr.includes(i)) {
count++;
}
}
console.log(count) // 3
サンプルコード
以下は、
「実行」ボタンをクリックすると、テキストフォームに入力されたアルファベットの母音の数を表示する
サンプルコードとなります。
※cssには「tailwind」を使用してます。関数はアロー関数を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
</head>
<script>
window.onload = () => {
btn.onclick = () => {
let m = txt.value.match(/[aeiouAEIOU]/gi)
if(m !== null ) foo.innerHTML = txt.value.match(/[aeiouAEIOU]/gi).length
}
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 class="font-semibold text-emerald-500 text-lg mr-auto">実行結果</h1>
<p id="foo" class="font-semibold text-lg mr-auto"></p>
<input
class="mb-2 shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
id="txt" type="text">
<button id="btn"
class="mb-2 md:mb-0 bg-transparent hover:bg-emerald-500 text-emerald-700 font-semibold hover:text-white py-2 px-4 border border-emerald-500 hover:border-transparent rounded">
実行
</button>
</div>
</div>
</body>
</html>
取得されていることが確認できます。
![](https://mebee.info/wp-content/uploads/2022/05/javascript-4.gif)
-
前の記事
mac コマンドで空のディレクトリだけを削除する 2022.10.06
-
次の記事
PostgreSQL VIEWを作成する 2022.10.07
コメントを書く