gpt4 book ai didi

javascript - 点击后计算字符串中每个元音的数量

转载 作者:行者123 更新时间:2023-12-01 02:59:51 25 4
gpt4 key购买 nike

为一个html文件编写一些js,我在其中输入一个句子(字符串)。当我单击一个按钮时,它会输出每个元音的数量,不包括 y 并且不注意标点符号。我不能使用 var 所以我尝试使用 let 来完成这项工作。我相信我走在正确的道路上,从元音 a 开始,但如果句子不包含 a,我会收到错误。我想不出下一步该做什么。有什么想法吗?

'use strict';

let vButton = document.querySelectorAll('#vowels');
vButton.forEach(function(blip) {
blip.addEventListener('click', function(evt) {
evt.preventDefault();
console.log('click');

let vowelString = document.getElementById('roboInput'),
sentence = vowelString.value;
if (sentence !== '') {
let aMatches = sentence.match(/a/gi).length;
alert("a - " + aMatches);
}
vowelString.value = '';

});
});
a {
cursor: pointer;
}

.well-robot {
min-height: 340px;
}

.input-robot {
width: 100%;
min-height: 100px;
}

.output-robot {
border: 1px solid #000000;
min-height: 150px;
margin-top: 10px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<div class="container">
<div class="alert alert-info">
Hello! I'm a smart robot. I can do many interesting things. Type something below and click a button to watch me work!
</div>
<div class="row">
<div class="col-sm-4">
<img src="./robot.gif">
</div>
<div class="col-sm-8 well well-robot">
<textarea id="roboInput" placeholder="Input something here!" class="input-robot"></textarea>
<div class="btn-group btn-group-justified">
<a class="btn btn-default" id="vowels">Count Vowels</a>
<a class="btn btn-default" id="anagrams">Count Anagrams</a>
<a class="btn btn-default" id="distance">Word Distance</a>
</div>
<div id="robotResult" class="output-robot">
</div>
</div>
</div>
</div>

最佳答案

当正则表达式不匹配时,.match()返回null,而不是空数组,因此无法获取长度。您需要检查一下。

let matches = sentence.match(/a/gi);
let matchLength = matches ? matches.length : 0;
alert('a - ' + matchLength);

关于javascript - 点击后计算字符串中每个元音的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46504356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com