我目前有一个here实现的简单搜索功能,该功能允许用户搜索课程。用户可以输入查询,多个查询之间用逗号分隔,如果每个标记化查询都存在匹配项(迭代完成),我将过滤结果:
search($event) {
var re = /\s*,\s*/;
let splitQuery = this.searchText.split(re);
let numQueries = splitQuery.length;
let tempCourses = this.courses;
for (var i = 0;i < numQueries; i ++){
tempCourses = this.rankAndFilter(tempCourses, splitQuery[i].toUpperCase())
}
this.courseResults = this.sortByRank(tempCourses);
我还希望所有查询在搜索结果中也突出显示,以便用户查看。这是original highlight pipe,我已尝试对其进行修改,但它不会返回突出显示的每个单词。
transform(value: string, args: string): any {
var re = /\s*,\s*/;
if (args && value){
let splitQuery = args.split(re);
let numQueries = splitQuery.length;
let returnedHighlighted: String = value;
console.log(`number of queries: ${numQueries}`)
for (var i = 0; i < numQueries; i++){
console.log(`${i}: ${splitQuery[i]}`)
let startIndex = value.toUpperCase().indexOf(splitQuery[i].toUpperCase());
if (startIndex != -1) {
let endLength = args.length;
let matchingString = value.substr(startIndex, endLength);
returnedHighlighted = returnedHighlighted.replace(matchingString, "<mark>" + matchingString + "</mark>");
}
}
return returnedHighlighted
}
return value; }
一个测试案例是查询linear algebra
返回89A Statistics
和54 Mathematics
,查询linear algebra, probability
返回两个课程,但突出显示单个单词,而查询{{ 1}}将仅返回linear algebra, probability, data science
并突出显示每个查询。
实际上,这将应用于数以万计的课程,因此,对于突出显示或过滤的时间效率的任何指针/实现,也将受到赞赏。
谢谢!
答案 0 :(得分:2)
您可以一步完成。创建一个regExpresion,以搜索不同的值,并替换为 value
@Pipe({ name: 'highlight' })
export class HighlightPipe implements PipeTransform {
transform(value: string, args: string): any {
if (args && value){
var re = new RegExp(args.split(',').join('|'),"gi");
//e.g. if args was linear,equa, the regExpr will become /linear|equa/gi
return value.replace(re,(x)=>"<mark>"+x+"</mark>");
}
return value;
}
}
注意:您必须检查是否使用特殊字符$,...
答案 1 :(得分:0)
以@Eliseo的答案为基础来处理诸如“查询”和“查询”之类的极端情况:
transform(value: string, args: string): any {
if (args && value){
let re_noSpace = /\s*,\s*/;
let queryList = args.split(re_noSpace).filter(String);
let re_matchQueries = new RegExp(queryList.join('|'),"gi");
return value.replace(re_matchQueries,(x)=>"<mark>"+x+"</mark>");
}
return value;
}