How to highlight text using javascript

后端 未结 13 2268
名媛妹妹
名媛妹妹 2020-11-22 02:32

Can someone help me with a javascript function that can highlight text on a web page. And the requirement is to - highlight only once, not like highlight all occurrences of

13条回答
  •  鱼传尺愫
    2020-11-22 03:10

    Simple TypeScript example

    NOTE: While I agree with @Stefan in many things, I only needed a simple match highlighting:

    module myApp.Search {
        'use strict';
    
        export class Utils {
            private static regexFlags = 'gi';
            private static wrapper = 'mark';
    
            private static wrap(match: string): string {
                return '<' + Utils.wrapper + '>' + match + '';
            }
    
            static highlightSearchTerm(term: string, searchResult: string): string {
                let regex = new RegExp(term, Utils.regexFlags);
    
                return searchResult.replace(regex, match => Utils.wrap(match));
            }
        }
    }
    

    And then constructing the actual result:

    module myApp.Search {
        'use strict';
    
        export class SearchResult {
            id: string;
            title: string;
    
            constructor(result, term?: string) {
                this.id = result.id;
                this.title = term ? Utils.highlightSearchTerm(term, result.title) : result.title;
            }
        }
    }
    

提交回复
热议问题