You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么字符串'Yes'的匹配是大小写敏感的?如何实现不区分大小写判断?

直接将用户输入的内容统一转换为全小写/全大写格式,再和相同大小写的目标字符串比较,即可实现不区分大小写的判断。

修改后的代码如下:

let cheer = prompt('Did the Team win?');

// toLowerCase()会把所有字符转为小写,转后和小写的'yes'比较即可
if(cheer.toLowerCase() != 'yes') {
    alert("We will win the next one!");
} else{
     alert("Lets Go Team");
}

你也可以选择转为大写后对比,使用toUpperCase()方法,判断条件写为cheer.toUpperCase() != 'YES',效果完全一致。

如果需要兼容用户点击prompt取消按钮的场景(此时cheer值为null,直接调用字符串方法会报错),可以把判断条件调整为(cheer || '').toLowerCase() != 'yes'即可。

内容的提问来源于stack exchange,提问作者M Appel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:15:01