简体   繁体   English

比较单词中的字母时,Javascript不区分大小写

[英]Javascript case insensitive when comparing a letter in a word

I'm have this exercise where a user enters a word then enters a letter to see how many times the letter appears in that word. 我有这个练习,用户输入一个单词,然后输入一个字母,看看该单词出现多少次。 This part of the project works just fine. 这部分项目运作得很好。 However, I want to make it case insensitive, as of right now it's not. 但是,我想让它不区分大小写,因为现在它不是。 I thought creating a variable for uppercase and one for lowercase then comparing both of those variables to i or to the letter variable would work. 我想创建一个大写变量和一个小写变量,然后将这些变量与i或字母变量进行比较。 However, it's making the counter double the amount of letters found in the word. 但是,它使计数器的数量增加了一倍。 Can someone help me? 有人能帮我吗? Here's my code: 这是我的代码:

 function checkWordAndLetter() { var userWord = $("#word").val(); console.log(userWord); var userLetter = $("#letter").val(); console.log(userLetter); var letterUpperCase = userLetter.toUpperCase(); var letterLowerCase = userLetter.toLowerCase(); var tally = 0; for (i = 0; i < userWord.length; i++) { if (userLetter == userWord[i] && i == letterUpperCase || letterLowerCase) { tally++; } } console.log(tally); $("#letterResults").html(" There are " + tally + " " + userLetter + "'s in the word " + userWord); console.log("apple"); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="mainPage"> <h2>Find the Letter in the Word</h2> <h4>Enter a word and select a letter to see how many times that letter appears in the word</h2> <p>Enter below:</p> <br/> Word: <input id="word" type="text" name="word"><br/><br/> Letter: <input id="letter" type="text" name="letter"><br/><br/> <br/> <br/> <button id="submit" type="button" name="submit" onclick="checkWordAndLetter()">submit</button> <p id="letterResults"></p> </div> 

The easiest option here, without changing the rest of your code , is to upper (or lower) case both sides of the equation so you are comparing like for like. 这里最简单的方法, 在不改变你的代码的其余部分 ,是上(或更低)的情况下,等式所以你是比较喜欢像的两侧

 function checkWordAndLetter() { var userWord = $("#word").val(); var userLetter = $("#letter").val(); var userWordUpper = userWord.toUpperCase(); var userLetterUpper = userLetter.toUpperCase(); var tally = 0; for (var i = 0; i < userWord.length; i++) { if (userLetterUpper == userWordUpper[i]) { tally++; } } $("#letterResults").html(" There are " + tally + " " + userLetter + "'s in the word " + userWord); } $("#word,#letter").change(checkWordAndLetter) checkWordAndLetter(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='text' id='word' value='hello'/> <input type='text' id='letter' value='l' /> <div id='letterResults'></div> 


In your original code, this line: 在您的原始代码中,此行:

if (userLetter == userWord[i] && i == letterUpperCase || letterLowerCase) {

could have been: 可能是:

if (letterUpperCase == userWord[i] || letterLowerCase == userWord[i]) {

Another option might be to use .split() which separates the string into an array by breaking on the specified character. 另一种选择可能是使用.split() ,它通过打破指定的字符将字符串分隔成一个数组。 Normally this would be , , but you can use any letter: 通常这会是,但你可以使用任何字母:

var tally = userWordUpper.split(userLetterUpper).length - 1;

 function checkWordAndLetter() { var userWord = $("#word").val(); var userLetter = $("#letter").val(); var userWordUpper = userWord.toUpperCase(); var userLetterUpper = userLetter.toUpperCase(); var tally = userWordUpper.split(userLetterUpper).length - 1; $("#letterResults").html(" There are " + tally + " " + userLetter + "'s in the word " + userWord); } $("#word,#letter").change(checkWordAndLetter) checkWordAndLetter(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='text' id='word' value='hello' /> <input type='text' id='letter' value='l' /> <div id='letterResults'></div> 


A further option would be use to a regex (edit: see Rory's answer, no need to repeat here) - the benefit of a regex is that you don't need to convert to upper/lower first. 另一种选择是用于正则表达式(编辑:请参阅Rory的答案,不需要在此重复) - 正则表达式的好处是您不需要先转换为上/下。

If you want to count how much a letter appears in a word case-insensitively, downcase the word and the letter before iterating through the word. 如果你想计算一个字母在一个单词不区分大小写中出现多少,那么在迭代单词之前将单词字母放在一边。 In this way you will be comparing the same letters. 通过这种方式,您将比较相同的字母。 Example: 例:

let tally = 0;
let letter = "a";
let word = "cAaatttt";
word = word.toLowerCase();
letter = letter.toLowerCase();
for (let i = 0; i < word.length; i++) {
    if (word[i] === letter) tally++;
}

To do what you require with your current code is to convert both the word and letter strings to match cases, then do the comparison. 要使用当前代码执行所需操作,请将单词和字母字符串转换为匹配大小写,然后进行比较。 You can use toLowerCase() or toUpperCase() to do that. 您可以使用toLowerCase()toUpperCase()来执行此操作。

However you can simplify the code even further than that by creating a Regular Expression and using the case-insensitivity flag ( i ) along with match() , like this: 但是,您可以通过创建正则表达式并使用大小写不敏感标记( i )以及match()进一步简化代码,如下所示:

 $('#submit').click(function() { var userWord = $("#word").val(); var userLetter = $("#letter").val(); var re = new RegExp(userLetter, 'gi'); var tally = userWord.match(re).length; $("#letterResults").html(`There are ${tally} ${userLetter}'s in the word ${userWord}`); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="mainPage"> Word: <input id="word" type="text" name="word"><br/><br/> Letter: <input id="letter" type="text" name="letter"><br/><br/> <button id="submit" type="button" name="submit">submit</button> <p id="letterResults"></p> </div> 

Also note the use of an unobtrusive event handler here instead of the outdated on* event attribute, which you should avoid using. 还要注意在这里使用不显眼的事件处理程序而不是过时on* event属性,您应该避免使用它。

Convert the word to lowercase and use the lowercase letter to check. 将单词转换为小写并使用小写字母进行检查。 You don't need to do uppercase === letter || lowercase === letter 你不需要做uppercase === letter || lowercase === letter uppercase === letter || lowercase === letter . uppercase === letter || lowercase === letter Another issue is your if statement as others have pointed out already. 另一个问题是你的if语句,正如其他人已经指出的那样。

You could also use RegExp for this in one line: 您也可以在一行中使用RegExp:

const letter = 'a'
const word = 'pizza potatoes and hamburgers'
const reg = new RegExp(letter, 'gi')
const count = (word.match(reg) || []).length // 4, 0 if no letters found

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM