0

I have stored input text value into a variable with id name=search-query. And then I am searching through the JSON data to find any matching result and then output the result on the screen. Is there a way which I can bold the word which match the 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;
          } 
});   
}   
user21
  • 1,261
  • 5
  • 20
  • 41

3 Answers3

3

You need to use a $& backreference that returns the whole match value, but also pay attention that the first argument to replace method is a RegExp, not the search string:

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

Demo:

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>";
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

I'm thinking that

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

should be

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

Is that what you wanted?

A. L
  • 11,695
  • 23
  • 85
  • 163
  • For search query of 'a', in the result, it is printing German Funds. I does not want the word to print out, instead I want like a to be bold. I'm using angular JS for the code. – user21 Sep 01 '16 at 23:42
1

content=document.getElementById("content");

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

Try this one

v.name.innerHTML=v.name.innerHTML.replace(/search/gi,"<b>$&</b>");
Vijai
  • 2,369
  • 3
  • 25
  • 32
  • It didn't work. because I am output the answer in the ng-app element. It is reading the as in html word – user21 Sep 01 '16 at 23:43