0

我从一小部分学校开始,然后我想测试输入的值是否与其中一所学校匹配。到目前为止,这是我的代码:

    var $schools = [
     'University of Tennessee-Knoxville',
     'Maryville College',
     'Cleveland State Community College',
     'East Tennessee State University'
    ];   
    var $searchBar = $('input.searchBar');
    $searchBar.keyup(function(){
         var $searchValue = $searchBar.val();
         for (var x = 0; x < $schools.length; x++) {
             var $schoolLC = $schools[x].toLowerCase();
             var $searchLC = $searchValue.toLowerCase();
             var $searchingValue = new RegExp('.*' + $searchLC + '.*');
             if ($schoolLC.match($searchingValue)) {
                 console.log($searchLC);
             }
         }
     });

但显然有些地方是错误的(我相信我的 RegExp),因为它从不控制台记录 $searchLC。

非常感谢!!

4

4 回答 4

2

这不是

if ($searchLC.match($searchingValue)) {

应该是

if ($schoolLC.match($searchingValue)) {
于 2013-02-01T16:11:04.650 回答
1

我认为您需要转义所有 RegEx 特殊字符:

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

...
var $searchingValue = new RegExp('.*' + escapeRegExp($searchLC) + '.*');
...
于 2013-02-01T16:10:49.357 回答
1

试试这个:现场演示

for (var x = 0; x < $schools.length; x++) {
    var $schoolLC = $schools[x].toLowerCase();
    var $searchLC = $searchValue.toLowerCase();
    var $searchingValue = new RegExp('.*' + $searchLC + '.*');
    if ($schoolLC.match($searchingValue)) {
        alert($schoolLC);
    }
}
于 2013-02-01T16:16:34.037 回答
1

好吧,对于这个特定的示例,您可以使用 indexOf 而不是使用 match,以便您的代码变为

var $schools = [
 'University of Tennessee-Knoxville',
 'Maryville College',
 'Cleveland State Community College',
 'East Tennessee State University'
];   
var $searchBar = $('input.searchBar');
$searchBar.keyup(function(){
     var $searchValue = $searchBar.val();
     for (var x = 0; x < $schools.length; x++) {
         var $schoolLC = $schools[x].toLowerCase();
         var $searchLC = $searchValue.toLowerCase();
         if ($schoolLC.indexOf($searchLC) >= 0) {
             console.log($searchLC);
         }
     }
 });
于 2013-02-01T16:19:14.603 回答