匹配字符串的每次使用

时间:2013-03-08 20:09:19

标签: javascript regex match

我正在开发一个待办事项列表应用程序,用户可以将该列表项添加到网页中,还可以搜索待办事项列表项。下面我正在研究搜索功能。现在发生的事情是我在页面上添加一个li项目,上面写着“你找到了”+用户搜索的名称+与该特定项目相匹配的任务。但是,我不知道该怎么做才能匹配使用该名称的每个列表项。例如,我可以让一个名叫Bob的人做三个不同的任务。现在这个搜索只匹配第一个,但我想匹配所有三个。有什么建议?

function search() {
   var searchTerm = document.getElementById("search").value;
   searchTerm = searchTerm.trim();

   if(searchTerm == null || searchTerm == "") {
   alert("Please enter a string to search for");
   return;
   }
   else {
     var todoObj = undefined;
     results = undefined;
     re = undefined;

   for(var i = 0; i < todos.length; i++) {
     todoObj = todos[i];
     re = new RegExp(searchTerm, "ig");
     resultsOne = todoObj.who.match(re);
     if(resultsOne) {
       var ul = document.getElementById("test");
       var li = document.createElement(li);
       li.className = "listItem";  
       li.innerHTML = "You found " + todoObj.who + " who needs to " + todoObj.task; 
       ul.appendChild(li);    
       }
      }      
     }    
    }

1 个答案:

答案 0 :(得分:1)

保留匹配的待办事项的临时列表,最后,最后输出结果:

var matchedTodos = []; // temporary list of matched todos

for(var i = 0; i < todos.length; i++) {
     todoObj = todos[i];
     re = new RegExp(searchTerm, "ig");
     resultsOne = todoObj.who.match(re);
     if(resultsOne) {
         // found a match, add it to our temporary list
         matchedTodos.push(todoObj);
     }
 } 

// now output the matched todos

if (matchedTodos.length > 0) {
    var ul = document.getElementById("test");
    var li = document.createElement("li");
    li.className = "listItem";  
    var tasks = '';
    var todoObj = null;
    for(var j = 0; j < matchedTodos.length; j++) {
        todoObj = matchedTodos[j];
        tasks += todoObj.task + ', ';
    }
    li.innerHTML = "You found " + todoObj.who + " who needs to " + tasks; 
    ul.appendChild(li);  
}

您希望输出类似于"You found Bob who needs to clean his room, take a bath, sleep"。您必须添加一些逻辑,以便为句子获取正确数量的,逗号:P

编辑:将它们全部作为单独的列表项:

var matchedTodos = []; // temporary list of matched todos

for(var i = 0; i < todos.length; i++) {
     todoObj = todos[i];
     re = new RegExp(searchTerm, "ig");
     resultsOne = todoObj.who.match(re);
     if(resultsOne) {
         // found a match, add it to our temporary list
         matchedTodos.push(todoObj);
     }
 } 

// now output the matched todos

if (matchedTodos.length > 0) {
    var ul = document.getElementById("test");
    var todoObj = null;
    for(var j = 0; j < matchedTodos.length; j++) {
        var li = document.createElement("li");
        li.className = "listItem";  
        todoObj = matchedTodos[j];
        li.innerHTML = "You found " + todoObj.who + " who needs to " + todoObj.task;
        ul.appendChild(li);  
    } 
}