我已将输入文本值存储到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;
}
});
}
答案 0 :(得分:2)
您需要使用返回整个匹配值的$&
反向引用,但也要注意replace
方法的第一个参数是RegExp,而不是search
字符串:< / p>
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>";
}
&#13;
答案 1 :(得分:1)
我在想
"<b>search</b>");
应该是
var name = v.name.replace(search,
"<b>" + search + "</b>");
这就是你想要的吗?
答案 2 :(得分: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>");