从单词的开头有和没有空格的javascript单词搜索

时间:2015-01-13 22:27:22

标签: javascript regex search full-text-search

我正在尝试编写一个搜索功能,允许用户输入以下标准之一来返回'ho chi minh city'。对我来说棘手的是它必须始终搜索任何单词的开始。除此之外,它还必须与其他语言一起使用,但如果我能让拉丁字符工作至少是一个开始。

                //ho chi minh city
                //hochiminhcity
                //chi minh
                //chiminh
                //chiminhcity
                //chi minh city
                //ho
                //chi
                //minh
                //city

            containsTerm: function containsTerm (needle, haystack) {

                var _this = LocationPickerCtrl,
                    ndl = _this.formatStr(stringHelper.escapeRegExp(needle)),
                    re = new RegExp('(?:^|\\s)' + ndl, 'gi'),
                    found = false,
                    len,
                    key = _this.formatStr(haystack.Key),
                    name = _this.formatStr(haystack.Name);

                //check airport code
                if (key.indexOf(ndl) > -1) {
                    found = true;
                }

                //start of word
                if (re.test(name)) {
                    found = true;
                }

                if (name.indexOf(' ') > -1) {

                    if (name.replace(/\s/g, '').indexOf(needle) === 0) {
                        found = true;
                    }

                }

return found

}

非常感谢任何帮助。提前谢谢!

2 个答案:

答案 0 :(得分:0)

没有及时看到你需要正则表达式:(

var words = ['ho', 'chi', 'minh', 'city'];

var hochiming = function hochiming(words, input) {

  var data = input;
  var match = false;

  for (var i = 0; i < words.length; i++) {
    if (data.length === 0) {
      return match;
    } else if (data.substring(0, words[i].length) === words[i]) {
      match = true;
      data = data.substring(words[i].length);
      if (data[0] === " ") {
        data = data.substring(1);
      }
    } else if (match) {
      return false;
    }
  }
  return match;
}

var data = ['hochiminhcity', 'chi minh', 'chiminh', 'chiminhcity', 'chi minh city', 'ho', 'chi', 'minh', 'city'];
data.forEach(function(entry) {
  console.log('result:', hochiming(words, entry));
});

console.log('mistakes:');
(['ho chi minh ci', 'm aezfam', 'hochimineahcity', ' minhchi']).forEach(function(entry) {
  console.log('result:', hochiming(words, entry));
});

答案 1 :(得分:0)

如果你采用正则表达式路线,可以这样做 -

 # /(?=[hcm])(?:(?:ho)?\s*chi\s*minh(?:\s*city)?|(?:ho|chi|minh|city))/

 (?= [hcm] )                           # Start at a 'h', 'c', or 'm'
 (?:
      (?: ho )?                             # Optional 'ho'
      \s* chi \s* minh                      # Must have 'chi minh'
      (?: \s* city )?                       # Optional 'city'
   |                                      # or, 
      (?: ho | chi | minh | city )          # One of either 'ho','chi','minh', or 'city'
 )