如何设置案例敏感文本输入?

时间:2016-01-31 02:17:22

标签: javascript case case-insensitive

我的朋友正在开发一个有趣的Javascript Web应用程序,您可以在文本框中键入内容,然后计算机会返回结果,但它区分大小写。他可以让它不区分大小写吗?我们试图使用:

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

JavaScript case insensitive string comparison上,但他无法弄清楚如何使用它。

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

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

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

}

3 个答案:

答案 0 :(得分:0)

只需在变量后面添加.toUpperCase()

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

变为:

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

或只是:

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

答案 1 :(得分:0)

您可以这样使用,例如在第一个else-if块:

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

应用于字符串的函数toUpperCase返回它的大写版本,因此对于No,它将为NO。如果密码变量包含单词no的任何小写组合,例如" No"," nO"," NO"或"不",然后password.toUpperCase()将是"否"。 前面的代码相当于

{{1}}

答案 2 :(得分:0)

如果您要这样做,请使用switchtoLowerCasetoUpperCase之间唯一真正的区别在于,案例行中的值不会向您大喊大叫。

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')
    }
}
相关问题