繁体   English   中英

如何在JavaScript中进行不区分大小写的比较?

[英]How do I do case-insensitive comparisons in JavaScript?

我正在做一个简单的switch功能:

var game = prompt("What game do you want to play?");

switch(game) {
    case 'League of Legends':
        console.log("You just played that!");
    //more case statements snipped... //
    break;
}

如果用户将league of legends ,而不是League of Legends将它赶上或将它在我的所有情况下重置为默认的答案吗? 此外,我将如何更改它,以便大写和不大写的两个答案都起作用?

字符串比较是大小写敏感的,因此你不应该使用大写一切yourString.toUpperCase()或小写与yourString.toLowerCase()如果你的代码需要区分大小写。

打开游戏的小写版本:

switch (game.toLowerCase()) {
  case 'league of legends':
    console.log("You just played that!");
    break;
}

您可以使用String.toLowerCase()String.toLocaleLowerCase()

game.toLowerCase();

String.toLowerCase()

在javascript中,字符“ L”不等于字符“ l”。 因此,“英雄联盟”与“英雄联盟”不匹配。 通过将用户输入转换为所有小写字母,然后将其与switch语句中的小写字符串匹配,可以保证程序不会基于大小写进行区分。

您的代码与toLowerCase()

var game = prompt("What game do you want to play?");
game = game.toLowerCase();

switch(game) {
    case 'league of legends':
        console.log("You just played that!");
    //more case statements snipped... //
    break;
}

字符串“传奇联盟”和“传奇联盟”是不同的,因此在所有案例的底部都将使用默认值。

要使其正常工作,您可以使用

switch(game.toUpperCase()) {
    case 'LEAGUE OF LEGENDS':
        console.log("You just played that!");
    //more case statements snipped... //
    break;
}

暂无
暂无

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

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