javascript - 如何检查特定字母的输入值及其计数
问题描述
我想检查元音字母的输入值,然后计算其中的元音数量。
我只知道如何检查元音的输入,我发现很难知道元音的数量,我希望能够写:“这篇文章包含 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>
解决方案
正则表达式可以匹配元音,然后您可以检查匹配的数量。
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>
推荐阅读
- javascript - 遍历对象数组并获得一个新的对象数组
- sapui5 - 我们可以将 Node 包包含到 UI5 工具中吗
- django - 如何用 Django 实现 Angular
- microsoft-teams - 无法通过导航器连接到团队帐户
- javascript - 是的验证库 TypeError:yup__WEBPACK_IMPORTED_MODULE_0__ 不是函数
- c# - c#.net 中的 Block.io 支付网关集成
- sql - 如何使用正则表达式选择分组
- python - 按日期顺序组织数据行 Pandas Python
- laravel - 在 laravel 中使用模型不起作用,但在使用路由时起作用
- vue.js - fs 包不在 nuxt 的客户端