we have a rich text field in one of our objects that contains an html-document. I have created a search page and a user can click on a 'preview'-button which opens the html in a lightbox. I want to highlight the search terms, but I want to do it case sensitive. So far I came up with this ('a' contains the html and is a string):

string replaceToken = '(?i)'+highlightTerm;
a = a.replaceAll(replaceToken,'<span class="highlight">'+highlightTerm+'</span>');

This does replace all occurrences regardless of the case. However it replaces them with whatever the user searched for. So if a user searched for 'DoOr' it will highlight 'door' as 'DoOr'. But I want to highlight the original word without changing it. Any thoughts on that?


2 Answers 2


Here's a rough pass at a solution. (Care of the original requestor who posted the answer in the question)

boolean all_occurences_processed = false;
integer pos1 = 0;
integer pos2 = 0;
string v1,v2,v3;
integer newpos = 0;

for (String hlt:Highlightsterms) {
  all_occurences_processed = false;
  while (!all_occurences_processed) {
    if ((pos1!=-1) && (pos1>newpos)) {
      v1 = a.substring(0, pos1);
      v2 = a.substring(pos1, pos2);
      v3 = a.substring(pos2);
      a = v1+'<span class="hl">'+v2+'</span>'+v3;
      newpos = pos2+24;
    } else {
      all_occurences_processed = true;

Use Pattern and Matcher classes. The Apex documentation actually just links to the java doc: http://docs.oracle.com/javase/1.5.0/docs/api/index.html?java/util/regex/Pattern.html

 * @description Wraps matched terms in a string with a span.
 * @param       String toHighlight   - the input markup to highlight with spans
 * @param       String highlightTerm - the regex to match against toHighlight
 * @return      String - the highlighted version of toHighlight
public static String highlightTerms(String toHighlight, String highlightTerm) {
    Matcher match = Pattern.compile('(?i)(' + highlightTerm + ')').matcher(toHighlight);
    String matched;
    String highlight;

    while(match.find()) {
        matched     = match.group(0);
        highlight   = '<span class="highlight">' + matched + '</span>';
        toHighlight = toHighlight.replace(matched, highlight);

    return toHighlight;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .