If语句检查字母的大小写

If statement checks regardless of the case of the letters

本文关键字:大小写 语句 检查 If      更新时间:2023-09-26

我想让我的if语句更灵活。如果我在输入框中输入了一个准确的信息,我的语句就会触发,但如果用户将其输入为小写或大写,则无法检测到。以下是代码。

var find = _.findWhere($scope.allCast, {name: castName});
            if(!find){
                var cast = {
                    cpPortfolioItemId: id,
                    name: castName,
                    job: 'cast',
                    role: castRole
                };
                ContentAssessmentFactory.addCastDetail(cast);
            }else{
                $window.alert('Cast name is already exist.');
            }

您可以使用_.filter()cast.namecastName转换为小写或大写。

//Return you an array of matched elements
var find = _.filter($scope.allCast, function(cast){
    //Convert both text in lower case and compare
    //If required you can use .trim() like castName.trim().toLowerCase() to strip whitespace 
    return cast.name.toLowerCase() == castName.toLowerCase();
});
if(find.length == 0){
    var cast = {
        cpPortfolioItemId: id,
        name: castName,
        job: 'cast',
        role: castRole
    };
    ContentAssessmentFactory.addCastDetail(cast);
}else{
    $window.alert('Cast name is already exist.');
}

除了确保字符串处于相同的大小写之外,您还需要从要测试的字符串中去掉开始和结束的空白(如果有的话)。

使用trim()方法:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

最简单的方法是在比较时将比较的文本(用户输入和存储的数据)转换为小写或大写——这样无论别人如何键入内容都无关紧要。

http://www.mediacollege.com/internet/javascript/text/case-uppercase.html