Django: Highlight Search Results
Aug 10, 2020 | 1168 views
Solution refer to below links
- stackoverflow: how-to-highlight-searched-queries-in-result-page-of-django-template
- Custom template tags and filters
- Highlight matched search term
Python re.sub() case insensitive replace coding example:
In [54]: re.sub('(%s)'%re.escape('hE'), r'<abc>\g<1></abc>', 'hello', flags=re.IGNORECASE)
Out[54]: '<abc>he</abc>llo'
In [56]: re.sub('(%s)'%re.escape('hE.'), r'<abc>\g<1></abc>', 'he.llo', flags=re.IGNORECASE)
Out[56]: '<abc>he.</abc>llo'
Or another version (Here we exclude URL replacement from HTML text):
pattern = re.compile('(^%s|[\s]%s|%s[\s])' % tuple([re.escape(word),]*3), re.IGNORECASE)
highlighted = pattern.sub(r'<span class="highlight">\g<1></span>', highlighted)
Regex resource refer to: