字符串比较不起作用

String compare is not working

本文关键字:不起作用 比较 字符串      更新时间:2023-09-26

为什么我每次都不匹配..这段代码有什么问题

var CourseDesc = 'Master of Computer Application'
var str = CourseDesc.split(" ");
alert(str[0]);
var str2 = 'Master';
if(str == str2){
    alert("Matched");
}else{
    alert("Not Matched");
}

有人面对过这个吗??

String.Split 方法返回一个包含子字符串的数组。因此,您的str变量是数组而不是字符串。

if(str[0] == str2)

var CourseDesc = 'Master of Computer Application'
var str = CourseDesc.split(" ");
alert(str[0]);
var str2 = 'Master';
if(str[0] == str2){
    alert("Matched");
}else{
    alert("Not Matched");
}

JSFiddle

var CourseDesc = 'Master of Computer Application'
var str = CourseDesc.split(" ");
alert(str[0]);
var str2 = 'Master';
if(str == str2){ 
 alert("Matched");
}else{
 alert("Not Matched");
}

str 是数组,如果你想将 CourseDesc 与任何关键字匹配,你可以尝试 for 循环

var CourseDesc = 'Master of Computer Application'
var str = CourseDesc.split(" ");
var str2 = 'Master';
for(var i=0 ;i<str.length; i++){
  alert(str[i]);
   if(str[i] == str2){ 
     alert("Matched");
   }else{
     alert("Not Matched");
   }
}

从这个问题中不清楚 OP 是否只对匹配主字符串中的第一个单词感兴趣,但是,如果您只想知道关键字 (str2) 是否在第一个字符串拆分结果中的任何位置(如前所述,这是一个数组),您可以只查找索引。

或者,如演示中的第二个代码块所示,您可以只匹配原始字符串而不进行拆分:

var CourseDesc = 'Master of Computer Application'
var str = CourseDesc.split(" ");
var str2 = 'Master';
if (str.indexOf(str2) != -1) {
  alert("Matched");
} else {
  alert("Not Matched");
}
var str3 = 'Master of Computer Application';
var str4 = 'Master';
if (str3.match(str4)) {
  console.log("Matched");
} else {
  console.log("Not Matched");
}