0

我已将输入文本值存储到 id name=search-query 的变量中。然后我正在搜索 JSON 数据以找到任何匹配的结果,然后将结果输出到屏幕上。有没有一种方法可以加粗匹配 search-query.val 的单词?

<body ng-app="products" ng-controller="ctrl"> 

 <input type="text" id="search-query" name="query" placeholder="Enter product name"></input>
 <tbody>
       <tr ng-repeat="result in searchResult|orderBy:order:reverse" >  
          <td >
               <a ng-href="{{result.link}}" target="_blank">
                    <span ng-bind="result.name" target="_blank"></span> 
                </a>
          </td>
          <td  ng-bind="result.type"></td> 
        </tr>  
 </tbody> 
</body>

var app2 = angular.module('products', []);
app2.controller('ctrl', function($scope) {  
$scope.searchResult = []; 
$scope.submit = function(){  
    var search = $("#search-query").val();
    $.each(json.products, function(i, v) {
         var regex = new RegExp(search, "i");

         if (v.name.search(regex) != -1) {  

              // For the following line, is there a way which I can bold the word which match the search-query.val?
              var name = v.name.replace(search, "<b>search</b>");   // doesn't work

              $scope.searchResult.push({ name:name, type: v.type, link: v.url }); 
              return;
          } 
});   
}   
4

3 回答 3

2

您需要使用$&返回整个匹配值的反向引用,但还要注意replace方法的第一个参数是正则表达式,而不是search字符串:

var name = v.name.replace(regex, "<b>$&</b>"); 
                                     ^^

演示:

var search = "DOM";
var s = "No dom here";
var regex = new RegExp(search, "i");
if (s.search(regex) != -1) {  
   document.body.innerHTML = "<pre>" + s.replace(regex, "<b>$&</b>") + "</pre>";
}

于 2016-09-01T23:25:31.067 回答
1

我在想

var name = v.name.replace(search,"<b>search</b>");

应该

var name = v.name.replace(search,"<b>" + search + "</b>");

那是你想要的吗?

于 2016-09-01T23:23:42.273 回答
1

content=document.getElementById("content");

content.innerHTML=content.innerHTML.replace(/search/gi,"<b>$&</b>");
<div id="content">This my search text</div>

试试这个

v.name.innerHTML=v.name.innerHTML.replace(/search/gi,"<b>$&</b>");
于 2016-09-01T23:26:41.073 回答