首页 > 解决方案 > 如何检查特定字母的输入值及其计数

问题描述

我想检查元音字母的输入值,然后计算其中的元音数量。

我只知道如何检查元音的输入,我发现很难知道元音的数量,我希望能够写:“这篇文章包含 6 个元音”。

请看一下代码和帮助。

//Selecting document element
const voutText = document.querySelector('#vText');
const voutBtn = document.querySelector('#vSubBtn');
const voutBox = document.querySelector('#vOutput');

const vowelCount = 0;

const voutApp = () => {
    const vowel = ['A','E', 'I', 'O', 'U'];
    const voutTextView = voutText.value.toUpperCase();

    for (i = 0; i < voutText.value.length; i++) {
        voutBox.innerHTML = i;
    }
    if (voutTextView.includes('A')) {
        alert("Yey! we found vowels, your text contains the vowel sound 'A'");

    } else if (voutTextView.includes('E')) {
        alert("Yey! we found vowels, Your text contains the vowel sound 'E'");
    } else if (voutTextView.includes('I')) {
        alert("Yey! we found vowels, Your text contains the vowel sound 'I'");
    } else if (voutTextView.includes('O')) {
        alert("Yey! we found vowels, Your text contains the vowel sound 'O'");
    } else if (voutTextView.includes('U')) {
        alert("Yey! we found vowels, Your text contains the vowel sound 'U'");
    } else {
        voutBox.innerHTML = 'Your text contains no vowel sound';
    }

    voutText.value = '';
    voutBox.innerHTML = `Your text ${voutTextView} contains vowel sounds`;//I have to figure out how to get the vowel counts EG: Your text (Input Value) contains 6 vowels.
}

voutBtn.addEventListener('click', voutApp);
<div id="vHead">
    <h1>VOUT</h1>
    <p>Check a word for vowel sounds</p>
    <input id="vText" type="text" placeholder="Eg: Victor" value="Victor" required>
    <input id="vSubBtn" type="button" value="Check">
</div>
<div id="vOutput"></div>

标签: javascriptnode.js

解决方案


正则表达式可以匹配元音,然后您可以检查匹配的数量。

const input = document.querySelector('#vText');
const button = document.querySelector('#vSubBtn');
const output = document.querySelector('#vOutput');

button.onclick = () => {
    const inputText = input.value;
    const vowelCount = (inputText.match(/[aeiou]/gi) ?? []).length;
    output.textContent = `Your text ${inputText} contains ${vowelCount} vowel sounds`;
}
<div id="vHead">
    <h1>VOUT</h1>
    <p>Check a word for vowel sounds</p>
    <input id="vText" type="text" placeholder="Eg: Victor" value="Victor" required>
    <input id="vSubBtn" type="button" value="Check">
</div>
<div id="vOutput"></div>


推荐阅读