简体   繁体   English

如何进行不区分大小写的文本输入?

[英]How do I make a case in-sensitive text input?

My friend is working on a fun Javascript web application where you type something in the text box, and the computer returns you a result, but it is case-sensitive. 我的朋友正在开发一个有趣的Javascript Web应用程序,您可以在文本框中键入内容,然后计算机会返回结果,但区分大小写。 Can he make it case-insensitive? 他可以区分大小写吗? We have tried to use: 我们尝试使用:

var areEqual = string1.toUpperCase() === string2.toUpperCase();

which was on JavaScript case insensitive string comparison , but he cannot figure out how to use that. 这是JavaScript不区分大小写的字符串比较 ,但他不知道如何使用它。

function isValid() {
    var password = document.getElementById('password').value;

    if (password == "Shut Up")
        { alert('HOW ABOUT YOU!') }

    else if (password == "No")
        { alert('You just did') }

}

Just add the .toUpperCase() behind your variables: 只需在变量后面添加.toUpperCase()

else if (password == "No")
  {alert('You just did')}

becomes: 变为:

else if (password.toUpperCase() == "No".toUpperCase())
  {alert('You just did')}

or just: 要不就:

else if (password.toUpperCase() == "NO") //Notice that "NO" is upper case.
  {alert('You just did')}

You can use that this way, for example in the first else-if block: 您可以通过这种方式使用它,例如在第一个else-if块中:

 else if (password.toUpperCase() == "No".toUpperCase())
 {alert('You just did')}

The function toUpperCase, applied to a string, returns it's uppercased version, so for No it would be NO. 应用于字符串的函数toUpperCase返回其大写版本,因此对于No,它将为NO。 If the password variable holds any lower-upper case combo of the word no, such as "No", "nO", "NO" or "no", then password.toUpperCase() will be "NO". 如果password变量包含单词no的任何小写字母组合,例如“ No”,“ nO”,“ NO”或“ no”,则password.toUpperCase()将为“ NO”。 The previous code is equivalent to 前面的代码等效于

 else if (password.toUpperCase() == "NO")
 {alert('You just did')}

Please, if you're going to do this, use switch ! 请,如果您要执行此操作,请使用switch The only real difference between toLowerCase as opposed to toUpperCase here is that the values in the case lines won't be shouting at you. 在这里, toLowerCasetoUpperCase之间唯一的真正区别是案例行中的值不会对您大喊大叫。

function isValid() {
    var password = document.getElementById('password').value;

    switch (password.toLowerCase()){
        case "shut up":
            alert('HOW ABOUT YOU!');
        break;
        case "no":
            alert('You just did');
        break;
        case "okay":
            alert('Okay');
        break;

        // ...

        case "something else":
            alert('Really?');
        break;
        default:
            alert('Type Something Else')
    }
}

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

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