将子字符串与用户输入匹配

时间:2017-08-28 02:37:30

标签: javascript node.js

我有一个用户输入字符串,在此基础上,我执行switch的case语句。例如,如果用户类型字符串hello被带到case hello.Everything工作正常但是当我把string ='西姆拉天气'它需要'喜',因为它首先匹配。 我怎样才能更好地实现这一点?

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:

}

1 个答案:

答案 0 :(得分: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:
    }
}