2017-08-28 72 views
0

我有一个用户输入字符串,并就这个基础上,我执行switch.For例子case语句,如果用户输入字符串Hello被认为是区分hello.Everything工作正常,但是当我把串='西姆拉天气'它需要它'嗨',因为它匹配第一。 我该如何更好地执行此操作?匹配的子用户输入

var string = 'shimla weather'; 
var substring = ['hi', 'hello', 'weather', 'joke']; 
console.log(substring); 
var doubles = substring.map(function(x) { 
    if(string.includes(x)){ 
     expression = x; 
    } 
    });  
    console.log(expression);   
    switch(expression) { 
    case 'hi': 
    case 'hello' 
     console.log('hello'); 
     break; 
    case 'weather': 
    console.log('weather'); 
     break; 
    case 'joke': 
     console.log('joe'); 
     break; 
    default: 

} 
+0

的一种方法是从最长的'case's排序,以最短的字。 – Xufox

+0

你没有描述所需的行为。如果有多个匹配,你希望发生什么? – Marty

+0

是的,问题出现在多个匹配@马蒂的情况下。我想处理这个问题。 – art12345

回答

0

如果你想专注于文字,而不是子字内,你可以做到以下几点:

var string = 'shimla weather'; 
var substring = ['hi', 'hello', 'weather', 'joke']; 
var splittedWords = string.split(/\s+/); 
var isWordFound = false; 
substring.map(function(x) { 
    var index = splittedWords.indexOf(x); 
    if(index != -1){ 
     isWordFound = true; 
     word = splittedWords[index]; 
     matchFound(word); 
    } 
}); 

if(!isWordFound) { 
    // do whatever you want 
}  

function matchFound(word) { 
    switch(word) { 
     case 'hi': 
     case 'hello': 
      console.log('hello'); 
      break; 
     case 'weather': 
     console.log('weather'); 
      break; 
     case 'joke': 
      console.log('joe'); 
      break; 
     default: 
    } 
} 
+0

如果没有匹配的条目来此功能不会在这种情况下,@ Anshuman Jaiswal 对于前执行默认:字符串=“H” – art12345

+0

编辑答案,现在如果整个字未找到,如果你可以做任何你想做的'(isWordF )'块 –