Issue #5 resolved
Mike Orr
created an issue

Useful helper for webhelpers.html.tools .

{{{

!python

def highlight(s, sub, **attrs): """Highlight all occurrences of substring sub in string s by placing them in an HTML <span> with attrs attributes.

If either ``s`` or ``sub`` is None or empty, return ``s`` unchanged.
"""
if not s or not sub:
    return s
s_lower = s.lower()
sub_lower = sub.lower()
sub_length = len(sub_lower)
chunks = []
start = 0
while True:
    pos = s_lower.find(sub_lower, start)
    if pos == -1:
        chunks.append(s[start:])
        break
    end = pos + sub_length
    chunks.append(s[start:pos])
    tag = HTML.span(s[pos:end], **attrs)
    chunks.append(tag)
    start = end
return literal("").join(chunks)

}}}

Comments (1)

  1. Log in to comment