Highlight the search text - angular 2

前端 未结 7 869
心在旅途
心在旅途 2020-12-01 05:22

A messenger displays the search results based on the input given by the user. Need to highlight the word that is been searched, while displaying the result. These are the h

7条回答
  •  被撕碎了的回忆
    2020-12-01 06:03

    The selected answer has the following issues:

    1. It will return undefined if there is nothing provided in the search string
    2. The search should be case insensitive but that should not replace the original string case.

    i would suggest the following code instead

    transform(value: string, args: string): any {
        if (args && value) {
            let startIndex = value.toLowerCase().indexOf(args.toLowerCase());
            if (startIndex != -1) {
                let endLength = args.length;
                let matchingString = value.substr(startIndex, endLength);
                return value.replace(matchingString, "" + matchingString + "");
            }
    
        }
        return value;
    }
    

提交回复
热议问题